Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the ternary operator short circuit in a defined way

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?

like image 528
Glenn Teitelbaum Avatar asked Oct 29 '15 14:10

Glenn Teitelbaum


1 Answers

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.

like image 180
Shafik Yaghmour Avatar answered Sep 19 '22 13:09

Shafik Yaghmour