The relational and equality operators are left-associative in C. Consequently, C, unlike many other languages, allows chaining of relational and equality operators. C99, Section 6.5.8 "Relational operators", paragraph 6 has a footnote (92), which says
The expression a<b<c is not interpreted as in ordinary mathematics. As the syntax indicates, it means (a<b)<c; in other words, "if a is less than b, compare 1 to c; otherwise, compare 0 to c".
...
Code Block | ||
---|---|---|
| ||
if ( (a < b) && (b < c) ) /* clearer, and probably what was intended */ /* ... */ if ( (a == b) && (a == c) ) /* ditto */ |
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 |
Automated Detection
Tool | Version | Checker | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
|
|
Related Guidelines
CERT C++ Secure Coding Standard: 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 |
Bibliography
\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 6.5.8 "Relational operators" Wiki Markup
Bibliography
...
03. Expressions (EXP) EXP14-C. Beware of integer promotion when performing bitwise operations on chars or shorts