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. C99, section 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
bgColor#ccccff
if ( (a < b) && (b < c) ) /* clearer, and probably what was intended */
/* ... */
if ( (a == b) && (a == c) ) /* ditto */

Automated Detection

...

Tool

Version

Checker

Description

Section

GCC

Include Page
c:GCC_V
c:GCC_V

 

Section

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

Other Languages

Related Guidelines

This rule appears in the C++ Secure Coding Standard as : 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.

...