...
This noncompliant code example uses an if
statement without braces to authenticate a user.
Code Block |
---|
|
int login;
if (invalid_login())
login = 0;
else
login = 1;
|
A developer might add a debugging statement to determine when the login is valid, but forget to add opening and closing braces.
Code Block |
---|
|
int login;
if (invalid_login())
login = 0;
else
printf("Login is valid\n"); /* debugging line added here */
login = 1; /* this line always gets executed, regardless of a valid login! */
|
...
In the compliant solution, opening and closing braces are used even when the body is a single statement.
Code Block |
---|
|
int login;
if (invalid_login()) {
login = 0;
} else {
login = 1;
}
|
...
This noncompliant code example has an if
statement nested in another if
statement without braces around if
and else
bodies.
Code Block |
---|
|
int privileges;
if (invalid_login())
if (allow_guests())
privileges = GUEST;
else
privileges = ADMINISTRATOR;
|
The indentation could lead the programmer to believe that a user is given administrator privileges only when the user's 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;
|
...
In the compliant solution, adding braces removes the ambiguity and ensures that privileges are correctly assigned.
Code Block |
---|
|
int privileges;
if (invalid_login()) {
if (allow_guests()) {
privileges = GUEST;
}
} else {
privileges = ADMINISTRATOR;
}
|
...