Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Braces also help ensure that macros with multiple statements are properly expanded. Such a macro should be wrapped in a do-while loop (see PRE10-C. Wrap multi-statement macros in a do-while loop); however, when the do-while loop is not present, braces can still ensure that the macro expands as intended.

Noncompliant Code Example

This noncompliant code example uses an if-else statement without braces to authenticate a user.

...

Due to the indentation of the code, it is difficult to tell that the code is not functioning as intended by the programmer, leading to a possible security breach.

Compliant Solution

Opening and closing braces are used even when the body is a single statement.

Code Block
bgColor#CCCCFF
int login;

if (invalid_login()) {
  login = 0;
} else {
  login = 1;
}

Noncompliant Code Example

When you have an if-else statement nested in another if statement, always put braces around the if-else.

...

This is a security loophole - users with invalid logins can still obtain administrator privileges.

Compliant Solution

Adding braces removes the ambiguity and ensures that privileges are correctly assigned.

Code Block
bgColor#CCCCFF
int privileges;

if (invalid_login()) {
  if (allow_guests()) {
    privileges = GUEST;
  } 
} else {
  privileges = ADMINISTRATOR;
}

Risk Assessment

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

EXP19-C

medium

probable

medium

P8

L2

References

Wiki Markup
\[[ISO/IEC 9899-1999|AA. References#ISO/IEC 9899-1999]\] Section 6.8.4, "Selection statements"
\[[MISRA 04|AA. References#MISRA 04]\] Rule 14.8
\[[GNU Coding Standards|http://www.gnu.org/prep/standards/standards.html#Syntactic-Conventions]\] Section 5.3, "Clean Use of C Constructs"