Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2022.2

...

More important, it is easy to forget to add braces when inserting additional statements into a body containing only a single statement, because the conventional indentation gives strong (but misleading) guidance to the structure.

Noncompliant Code Example

This noncompliant code example authenticates a user with an if statement that lacks braces:

...

The code's indentation disguises the functionality of the program, potentially leading to a security breach.

Compliant Solution

This compliant solution uses opening and closing braces even though the body of the if and else bodies of the if statement are single statements:

Code Block
bgColor#CCCCFF
int login;

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

Noncompliant Code Example

This noncompliant code example nests an if statement within another if statement, without braces around the if and else bodies:

...

Consequently, this defect allows unauthorized users to obtain administrator privileges.

Compliant Solution

This compliant solution uses braces to remove the ambiguity, consequently ensuring that privileges are correctly assigned:

Code Block
bgColor#CCCCFF
int privileges;

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

Applicability

Failure to enclose the bodies of if, for, or while statements in braces makes code error prone and increases maintenance costs.

Automated Detection

ToolVersionCheckerDescription
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.EXP52.BLKProvide a '{}' block for conditional statements
PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V6089
SonarQube
Include Page
SonarQube_V
SonarQube_V

S2681
S00121



Bibliography

...


...

Image Modified Image Modified Image Modified