If statements
Control statements like if
, else if
, for
, while
, switch
, and else
statements always have curly brackets on separate lines. Even if they are one line statements.
C++17 adds if
initalizers. Similar to for
loops, there should be a space in between the initializer and condition.
REASONING: There is a very important reason for this seemingly petty rule. It clarifies a lot of confusion.
For example, this code is very confusing at first glance:
With this style guide, the above code will become much clearer:
Another example of why this rule is absolutely important is because of what happend to OSX developers. They had some code which checked the signature of an SSL certificate. For those who don't know what that is, the function checked if an encryption was valid. Here was the code (in C:)
Notice that the second goto fail
always ran. This was a typo by OSX developers that actually opened up a HUGE security vulnerability. By always putting curly brackets, you prevent very hard-to-find errors such as this.
Logical Operators
When using logical operators such as &&
and ||
always put a space in between the operands. Single operand operators such as !
, -
, or ~
don't have a space.
See more details in the operators section.
Also, the same rules specified on the Line Length page apply to if
statements.
Else
If you have an else-if the closing bracket and the else goes on the same line. Spaces go after the brackets.
BAD:
GOOD:
Last updated