Versions Compared

Key

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

...

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

Code Block
bgColor#ffcccc
int login;

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

A maintainer might add a debug statement or other logic but forget to add opening and closing braces.:

Code Block
bgColor#ffcccc
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!

...

This compliant solution uses opening and closing braces even though the body of the if is a single statement.:

Code Block
bgColor#CCCCFF
int login;

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

...

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

Code Block
bgColor#ffcccc
int privileges;

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

...

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;
}

...