The relational and equality operators are left-associative, not non-associative as they often are in other languages. A comparison such as{{x<=y<=z}}, for example, is equivalent to (x<=y ? 1 : 0) <= z
, which is a different interpretation from that of ordinary mathematical notation. This allows a programmer to write an expression (particularly an expression used as a condition) that can be easily misinterpreted.
Noncompliant Code Example
While this noncompliant code example compiles correctly, it is unlikely that it means what the author of the code intended.
int a = 2; int b = 2; int c = 2; /* ... */ if (a < b < c) /* misleading, likely bug */ /* ... */ if (a == b == c) /* misleading, likely bug */
The expression a < b < c
evaluates to true, rather than false as its author probably intended, and the expression a == b == c
evaluates to false, rather than true as its author probably intended.
Compliant Solution
Treat relational and equality operators as if it were invalid to chain them.
if ( (a < b) && (b < c) ) /* clearer, and probably what was intended */ /* ... */ if ( (a == b) && (a == c) ) /* ditto */
Automated Detection
The GCC option -Wparentheses
warns if a comparison like x<=y<=z
appears. This warning is also enabled by -Wall
.
Other Languages
This rule appears in the C++ Secure Coding Standard as EXP17-CPP. Treat relational and equality operators as if they were nonassociative.
Risk Assessment
Incorrect use of relational and equality operators can lead to incorrect control flow.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
EXP09-A |
1 (low) |
1 (unlikely) |
2 (medium) |
P2 |
L3 |
03. Expressions (EXP) EXP30-C. Do not depend on order of evaluation between sequence points