Search code examples
cstandardsconditional-operator

Order of evaluation for ternary operator in C


I am aware that according to the standard, fun(++a, a) should be avoided since second argument is not well defined.

However, is this formulation safe:

(++a ? a : 10);

I tested this snippet and it works as expected, ie for a = -1 it evaluates as 10, and for any other a it evaluates as a+1. Is this well defined in the standard, or it strongly depends on the compiler?


Solution

  • This is well defined.

    In a ternary expression, the first part is evaluated first. Then based on that value, either the second or the third part is evaluated. So ++a is guaranteed to be evaluated before a is possible evaluated.

    This is explained in section 6.5.15p4 of the C standard:

    The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand(whichever is evaluated), converted to the type described below.