Do not use a semicolon after an if, for, or while condition because it typically indicates programmer error and can result in unexpected behavior.

Noncompliant Code Example

In this noncompliant code example, a semicolon is used immediately following an if condition:

if (a == b); {
  /* ... */
}

The statements in the apparent body of the if statement are always evaluated regardless of the result of the condition expression.

Compliant Solution

This compliant solution eliminates the semicolon and ensures that the body of the if statement is executed only when the condition expression is true:

if (a == b) {
  /* ... */
}

Applicability

Placing a semicolon immediately following an if, for, or while condition may result in unexpected behavior.

Automated Detection

ToolVersionCheckerDescription
PVS-Studio

7.33

V6063
SonarQube
9.9
EmptyStatementUsageCheck


Bibliography

[Hatton 1995]

§2.7.2, "Errors of Omission and Addition"



7 Comments

  1. But, but...   I could comply with this rule as follows:

    if (a == b) 
    {
      /* ... */
    }

    which can't possibly be what we intended.  Right? This rule appears to be broken as written.

    1. Dean: Made some edits and also renamed the guideline to address your concern.

      1. Made yet more edits and renamed the guideline yet again.

        Please re-review.

  2. Should point out that it could be difficult to find the issue especially in long statements such as this code sample:

    http://en.newinstance.it/2005/06/11/infamous-programming-errors-on-curly-braced-blocks/

     

    1. Perhaps, but this is one case where automatic detection is trivially easy.  Perhaps we should say that?

  3. If I remember correctly, PMD (http://pnd.sourceforge.net/) will catch errors like this.