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
Tool | Version | Checker | Description |
---|---|---|---|
PVS-Studio | 7.33 | V6063 | |
SonarQube | 9.9 | EmptyStatementUsageCheck |
Bibliography
§2.7.2, "Errors of Omission and Addition" |
7 Comments
Dean Sutherland
But, but... I could comply with this rule as follows:
/* ... */
}
which can't possibly be what we intended. Right? This rule appears to be broken as written.
Dhruv Mohindra
Dean: Made some edits and also renamed the guideline to address your concern.
Fred Long
Made yet more edits and renamed the guideline yet again.
Please re-review.
Dean Sutherland
Much better now.
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/
Fred Long
Perhaps, but this is one case where automatic detection is trivially easy. Perhaps we should say that?
Steven Scholnick
If I remember correctly, PMD (http://pnd.sourceforge.net/) will catch errors like this.