Versions Compared

Key

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

Opening and closing braces for if, for, or while statements should always be used, even if said statement has 's body contains only a single body linestatement.

Braces help improve the uniformity, and therefore readability of code.

More importantly, when inserting an additional statement in a body containing only a single linestatement, it is easy to forget to add braces when the indentation tends to give a strong (but probably misleading) guide to the structure.

...

This noncompliant code example does not use braces.

Code Block
bgColor#ffcccc
int login;

if (a)
  if (b)
    win()valid_login())
  if (!is_administrator())
    login = USER;
  else
    login = ADMINISTRATOR;

It works as expected by setting the login variable accordingly, depending if the login was valid or not.

However, when the programmer adds another statement to the body of the first if statement, the code functions differently.

Code Block
bgColor#ffcccc

int login;

if (valid_login())
  printf("Login Successful\n");  /* debugging line added here */
  if (!is_administrator())
    login = USER;
  else
    login = lose();
ADMINISTRATOR;

Because of the additional statement in the body of the first if statement, the user gains administrator rights automatically, without having to even provide valid login credentials.

Compliant Solution

Code Block
bgColor#CCCCFF
int login;

if (valid_login(a)) {
  if (b) {    printf("Login Successful\n");  /* debugging line added here */
    win();  if (!is_administrator()) {
    login = USER;
  } else {
    
login =   lose();  ADMINISTRATOR;
  }
}

Noncompliant Code Example

...