CertC-EXP13¶
Treat relational and equality operators as if they were nonassociative
Required inputs: IR
The relational and equality operators are left-associative in C. Consequently, C, unlike many other languages, allows chaining of relational and equality operators. Subclause 6.5.8, footnote 107, of the C Standard [ ISO/IEC 9899:2011 ], says:
The expression
a<b<cis not interpreted as in ordinary mathematics. As the syntax indicates, it means(a<b)<c; in other words, "ifais less thanb, compare 1 toc; otherwise, compare 0 toc."
These operators are left-associative , which means the leftmost comparison is performed first, and the result is compared with the rightmost comparison. This syntax allows a programmer to write an expression (particularly an expression used as a condition) that can be easily misinterpreted.
Noncompliant Code Example
Although 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, as its author probably intended, to false, and the expression a == b == c evaluates to false rather than, as its author probably intended, to true.
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 */ |
Risk Assessment
Incorrect use of relational and equality operators can lead to incorrect control flow.
| Rule | Severity | Likelihood | Detectable | Repairable | Priority | Level |
|---|---|---|---|---|---|---|
| EXP13-C | Low | Unlikely | Yes | Yes | P3 | L3 |
Related Guidelines
| SEI CERT C++ Coding Standard | VOID EXP17-CPP. Treat relational and equality operators as if they were nonassociative |
Bibliography
| [ ISO/IEC 9899:2011 ] | Subclause 6.5.8, "Relational Operators" |
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
chained_comparison |
Operand of ‘{}’ is itself a comparison |
None |
False |
Options¶
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
ignore_parenthesized_comparisons¶
ignore_parenthesized_comparisons : bool = False
(a < b) == c.