25

If you have the following:

if (x)
{
    y = *x;
}
else
{
    y = 0;
}

Then behavior is guaranteed to be defined since we can only dereference x if it is not 0

Can the same be said for:

y = (x) ? *x : 0;

This seems to work as expected (even compiled with -Wpedantic on g++)

Is this guaranteed?

6
  • 2
    Yes - The ternary operator is just syntactic sugar
    – Ed Heal
    Commented Oct 29, 2015 at 14:49
  • 7
    Yes. (Too short to be posted as an answer).
    – JSF
    Commented Oct 29, 2015 at 14:49
  • 2
    There's no "short circuit" in the ternary expression. And it doesn't prematurely evaluate or execute any branch either before the condition have been fully evaluated. Commented Oct 29, 2015 at 14:51
  • @EdHeal I can't think of what it would be syntactic sugar for. Commented Oct 29, 2015 at 14:53
  • 5
    @EdHeal But the conditional operator gives you an expression, not a statement. Commented Oct 29, 2015 at 14:56

1 Answer 1

34

Yes, only the second or third operand will be evaluated, the draft C++ standard section 5.16 [expr.cond] says:

Conditional expressions group right-to-left. The first expression is contextually converted to bool (Clause 4). It is evaluated and if it is true, the result of the conditional expression is the value of the second expression, otherwise that of the third expression. Only one of the second and third expressions is evaluated. Every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression.

1
  • 1
    So, x ? *x++ : 0 will not increment x iff x == 0 Commented Jul 15, 2019 at 4:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.