Do not use a semicolon on the same line as after an if, for, or while statement condition because this it typically indicates programmer error and can result in unexpected behavior.
Noncompliant Code Example
In this noncompliant code example, a semicolon is used on the same line as immediately following an if statement. condition:
| Code Block | ||
|---|---|---|
| ||
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
It is likely, in this example, that the semicolon was accidentally inserted.This compliant solution eliminates the semicolon and ensures that the body of the if statement is executed only when the condition expression is true:
| Code Block | ||
|---|---|---|
| ||
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 |
|---|
| Section |
|---|
| Section |
|---|
SEMICOL |
Related Guidelines
ISO/IEC TR 24772 "KOA Likely Incorrect Expressions"
MITRE CWE: CWE-480, "Use of Incorrect Operator"
Bibliography
...
| Parasoft Jtest |
| CERT.MSC51.NSIF | Do not place a semicolon immediately after an if, for, or while condition | ||||||
| PVS-Studio |
| V6063 | |||||||
| SonarQube |
| EmptyStatementUsageCheck |
Bibliography
§2.7.2, |
...
"Errors |
...
of Omission and Addition" |
...
omission and addition"EXP14-C. Beware of integer promotion when performing bitwise operations on integer types smaller than int 03. Expressions (EXP) EXP16-C. Do not compare function pointers to constant values