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
Parasoft Jtest
2025.2
CERT.MSC51.NSIFDo not place a semicolon immediately after an if, for, or while condition
PVS-Studio

7.40

V6063
SonarQube
9.9
EmptyStatementUsageCheck


Bibliography

[Hatton 1995]

§2.7.2, "Errors of Omission and Addition"



7 Comments

  1. Dean Sutherland

    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. Dhruv Mohindra

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

      1. Fred Long

        Made yet more edits and renamed the guideline yet again.

        Please re-review.

      2. Dean Sutherland

        Much better now.

  2. Dhruv Mohindra

    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. Fred Long

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

  3. Steven Scholnick

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