You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

The relational and equality operators are left-associative, not non-associative as they often are in other languages. A comparison such as{{x<=y<=z}}, for example, is equivalent to (x<=y ? 1 : 0) <= z, which is a different interpretation from that of ordinary mathematical notation. This allows a programmer to write an expression (particularly an expression used as a condition) that can be easily misinterpreted.

Noncompliant Code Example

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

int a = 2;
int b = 2;
int c = 2;
// ...
if ( a < b < c ) // condition #1, misleading, likely bug
// ...
if ( a == b == c ) // condition #2, misleading, likely bug

Condition #1 evaluates to true, rather than false as its author probably intended, and condition #2 evaluates to false, rather than true as its author probably intended.

Compliant Solution

Treat relational and equality operators as if it were invalid to chain them.

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

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP09-A

1 (low)

1 (unlikely)

2 (medium)

P2

L3

Automated Detection

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

Other Languages

This rule appears in the C++ Secure Coding Standard as EXP17-CPP. Treat relational and equality operators as if they were nonassociative.


      03. Expressions (EXP)      EXP30-C. Do not depend on order of evaluation between sequence points

  • No labels