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 C++ 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.
Code Block | ||
---|---|---|
| ||
int a = 2; int b = 2; int c = 2; // ... if ( a < b < c ) // condition #1, misleading, likely bug // ... if ( a == b == c ) // condition #2, misleading, likely bug |
While the code in the Non-Compliant Code Example compiles correctly, it is unlikely that it means what the author of the code intended. Condition #1 will evaluate Condition #1 evaluates to true, rather than false as its author probably intended, and condition #2 will evaluate evaluates to false, rather than true as its author probably intended.
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP09-A | 1 (low) | 1 (unlikely) | 2 (medium) | P2 | L3 |
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.
...