The relational and equality operators are left-associative in C. Consequently, C, unlike many other languages, allows chaining of relational and equality operators. The C standard, Section Subclause 6.5.8, paragraph 6, footnote 107, of the C Standard [ISO/IEC 9899:2011], 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."
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.
...
Although 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) /* misleading,Misleading; likely bug */
/* ... */
if (a == b == c) /* misleading,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.
...
Treat relational and equality operators as if it were invalid to chain them.:
| Code Block | 
|---|
|  | 
| if ( (a < b) && (b < c) ) /* clearer,Clearer and probably what was intended */
/* ... */
if ( (a == b) && (a == c) ) /* dittoDitto */
 | 
Risk Assessment
Incorrect use of relational and equality operators can lead to incorrect control flow.
| Rule | Severity | Likelihood | Detectable | 
|---|
Remediation Cost| Repairable | Priority | Level | 
|---|
| EXP13-C | Low | 
lowunlikelymediumP2Automated Detection
| Tool | Version | Checker | Description | 
|---|
| Astrée |  | chained-comparison | Fully checked | 
| ECLAIR |  | CC2.EXP13
 | Fully implemented | 
| GCC |  | 
 |  | 
 | Option -Wparentheseswarns if a comparison likex<=y<=zappears | 
. This | ; this warning is also enabled by -Wall | 
.ECLAIRECLAIRECLAIRexprprnsPRQA QA-C| EXP13-C | Checks for possibly unintended evaluation of expression because of operator precedence rules (rec. fully covered) 
 | 
| PVS-Studio |  | 
PRQAPRQA3392 3401  4111  4112  4113| | |  | RuleChecker_V | 
|---|
 |  | RuleChecker_V | 
|---|
 | 
 | chained-comparison | Fully checked | 
Fully implemented.Related Guidelines
Bibliography
Section | Subclause 6.5.8, "Relational Operators" | 
 ...
...
 Image Modified
Image Modified  Image Modified
Image Modified  Image Modified
Image Modified