Opening and closing braces for if
, for
, or while
statements should always be used, even if said statement's body contains only a single statement.
In the event that either of these statements are If an if
, while
, or for
statement is used in a macro, this implies that then the macro definition should not be concluded with a semicolon (see PRE11-C. Do not conclude macro definitions with a semicolon).
Braces help improve the uniformity , and therefore readability of code.
More importantly, when inserting an additional statement in a body containing only a single statement, it is easy to forget to add braces when the indentation tends to give a strong (but probably misleading) guide to the structure.
...
This noncompliant code example uses an if-else
statement without braces to authenticate a user.
Code Block | ||
---|---|---|
| ||
int login; if (invalid_login()) login = 0; else login = 1; |
The programmer adds A developer might add a debugging statement to determine when the login is valid, but forgets forget to add opening and closing braces.
...
Due to the indentation of the code, it is difficult to tell that the code is will not functioning function as intended by the programmer, leading to a possible security breach.
...
Noncompliant Code Example
When you have an if-else
statement nested in another if
statement, always put braces around the if-
and else
bodies.
This noncompliant code example does not use braces.
...