Does the ternary operator short circuit in a defined way
Asked Answered
V

1

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?

Viburnum answered 29/10, 2015 at 14:47 Comment(6)
Yes - The ternary operator is just syntactic sugarCrinoline
Yes. (Too short to be posted as an answer).Bareilly
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.Crony
@EdHeal I can't think of what it would be syntactic sugar for.Terbia
For the if statemetCrinoline
@EdHeal But the conditional operator gives you an expression, not a statement.Terbia
I
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.

Inconsonant answered 29/10, 2015 at 14:50 Comment(1)
So, x ? *x++ : 0 will not increment x iff x == 0Daphene

© 2022 - 2024 — McMap. All rights reserved.