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 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 */

Risk Assessment

Incorrect use of relational and equality operators can lead to incorrect control flow.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP09-A

1 (low)

1 (unlikely)

2 (medium)

P2

L3

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.

Related Guidelines

CERT C++ Secure Coding Standard: 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.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP09-A

1 (low)

1 (unlikely)

2 (medium)

P2

L3

Bibliography

Wiki Markup\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 6.5.8 "Relational operators"

Bibliography

...

      03. Expressions (EXP)      EXP14-C. Beware of integer promotion when performing bitwise operations on chars or shorts