Knowledge Base Article

Incorrect Results From Logical or Conditional Operation With Side-Effects

Description

The C2H Compiler always evaluates both operands of logical (&&, ||) and conditional (?:) operators. This is different from expected American National Standards Institute (ANSI) C behavior, where operands are evaluated left-to-right, and unnecessary operands are skipped.

For example, in the expression (i-- && j--), if the value of i is zero, ANSI C does not evaluate the right-hand-side (RHS) expression, and j is not decremented. By contrast, the C2H Compiler evaluates both sides, decrementing j.

The following expressions are other examples that might be affected by this issue:

if (i-- || j ) ...; a = ((cond == 1)? i : j );
Resolution

Use logical and conditional operations whose operators have no side effects. Operations with side effects include pre- and post- increment and decrement operations ( , --), memory operations (*, [], ., ->), and function calls.

Updated 2 months ago
Version 3.0
No CommentsBe the first to comment