Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The relational and equality operators are left-associative in C. Consequently, C, unlike many other languages, allows chaining of relational and equality operators. C99The C standard, Section 6.5.8 "Relational operators", paragraph 6 has a footnote (92), which says, footnote 107 [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 allows a programmer to write an expression (particularly an expression used as a condition) that can be easily misinterpreted.

Noncompliant Code Example

While Although this noncompliant code example compiles correctly, it is unlikely that it means what the author of the code intended.

Code Block
bgColor#FFcccc
langc

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 false, as its author probably intended, and the expression a == b == c evaluates to false , rather than true, as its author probably intended.

...

Code Block
bgColor#ccccff
langc

if ( (a < b) && (b < c) ) /* clearer, and probably what was intended */
/* ... */
if ( (a == b) && (a == c) ) /* ditto */

...

section

Option -Wparentheses warns if a comparison like x<=y<=z appears. This warning is also enabled by -Wall.

section

Tool

Version

Checker

Description

GCC

Include Page
GCC_V
GCC_V

 

Section

ECLAIR

Include Page
ECLAIR_V
ECLAIR_V
section

exprprns

section

Fully

Implemented

implemented.

Related Guidelines

CERT C++ Secure Coding Standard: EXP17-CPP. Treat relational and equality operators as if they were nonassociative

ISO/IEC 9899:19992011 Section 6.5.8 "Relational operators"

...