The relational and equality operators are left-associative in C. Consequently, C, unlike many other languages, allows chaining of relational and equality operators. Section Subclause 6.5.8, 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, "ifa
is 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.
...
Code Block | ||||
---|---|---|---|---|
| ||||
int a = 2; int b = 2; int c = 2; /* ... */ if (a < b < c) /* misleadingMisleading, likely bug */ /* ... */ if (a == b == c) /* misleadingMisleading, 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.
...
Code Block | ||||
---|---|---|---|---|
| ||||
if ( (a < b) && (b < c) ) /* clearerClearer, 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.
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
| CC2.EXP13 | Fully implemented | |||||||
|
| Option | |||||||
PRQA QA-C |
| 3392 | Fully implemented |
...
CERT C++ Secure Coding Standard | EXP17-CPP. Treat relational and equality operators as if they were nonassociative |
Bibliography
[ISO/IEC 9899:2011] | Section Subclause 6.5.8, "Relational Operators" |
...