〔Coding style〕Reasons to add the curly brackets behind if / for / while in C/C++
When using the if
, for
, or while
statements, it is important to include curly brackets even when there is only one line of code. This simple rule can greatly enhance the readability and structure of your code. Here are several reasons why:
Reason 1: Multi-line macro
Consider the following code:
if (condition)
DO_SOMETHING;
At first glance, it seems fine. However, if DO_SOMETHING
itself is a macro and the person who defined the macro did not wrap the whole paragraph with curly brackets, it could cause a logic error. For example:
#define DO_SOMETHING int n=0\
printf("%d", n);
Including curly brackets in the if
statement ensures that the entire macro is executed when the condition is true.
Reason 2: Changes on Git
Suppose you want to change the code during a code review. For instance, you might change this:
if (a > 0) a += b;
to this:
if (a > 0) {
a += b;
c++;
}
Your change is a simple addition of a single line of code, but for Git, it registers as a modification of four lines, including the line that the if
condition evaluates. Without curly brackets, the reviewer must confirm that the condition in the if
statement is consistent with the original code.
Reason 3: Consistency
Using curly brackets for all if
statements ensures consistency in your code style. You don't have to remember which statements require curly brackets and which do not. This keeps your code looking consistent and reduces unnecessary mental strain.
Reason 4: Readability
The inclusion of curly brackets makes the boundaries of the code clear, reducing eye strain and improving code readability.
Conclusion
It is best practice to always use curly brackets when using if
, for
, or while
statements, regardless of the number of lines of code involved. Doing so will help you avoid logic errors, facilitate code reviews, maintain consistency, and enhance the readability of your code.