...
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 the if
and else
bodies.:
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; } |
...
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP19-C | medium | probable | medium | P8 | L2 |
Related Guidelines
MISRA - C:2012 | Rule 14.815.6 (required) |
Bibliography
[GNU 2010] | Coding Standards, Section 5.3, "Clean Use of C Constructs" |
[ISO/IEC 9899:2011] | Section 6.8.4, "Selection Statements" |
...