Opening Use opening and closing braces for if
, for
, or while
statements should always be used even if when the body contains only a single statement. Braces improve the uniformity and readability of code.
More importantly, when inserting an additional statement it is easy to forget to add braces when inserting additional statements into a body containing only a single statement, it is easy to forget to add braces because the indentation gives strong (but misleading) guidance to the structure.
...
This noncompliant code example uses authenticates a user with an if
statement without braces to authenticate the userthat lacks braces.
Code Block | ||
---|---|---|
| ||
int login; if (invalid_login()) login = 0; else login = 1; |
...
Code Block | ||
---|---|---|
| ||
int login; if (invalid_login()) login = 0; else System.out.println("Login is valid\n"); // debugging line added here login = 1; // this line always gets executed regardless of a valid login! |
The code's indentation disguises the functionality of the program, potentially leading to a security breach.
Compliant Solution
In this This compliant solution , uses opening and closing braces are used even when though the body of the if is a single statement.
Code Block | ||
---|---|---|
| ||
int login; if (invalid_login()) { login = 0; } else { login = 1; } |
...
The indentation might lead the programmer to believe that a user is given users are granted administrator privileges only when the user's their login is valid. However, the else
statement actually attaches to the inner if
statement:
Code Block | ||
---|---|---|
| ||
int privileges; if (invalid_login()) if (allow_guests()) privileges = GUEST; else privileges = ADMINISTRATOR; |
As a resultConsequently, this defect allows unauthorized users to obtain administrator privileges.
Compliant Solution
In this This compliant solution , adding uses braces removes to remove the ambiguity and ensures , consequently ensuring that privileges are correctly assigned.
Code Block | ||
---|---|---|
| ||
int privileges; if (invalid_login()) { if (allow_guests()) { privileges = GUEST; } } else { privileges = ADMINISTRATOR; } |
Applicability
Not enclosing Failure to enclose the bodies of if
, for
, or while
statements in braces makes code maintenance error prone.
...