Does the ternary operator short circuit in a defined way

浪子不回头ぞ 提交于 2019-12-08 16:14:34

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/33417436/does-the-ternary-operator-short-circuit-in-a-defined-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!