三元运算符是否以定义的方式短路 [英] Does the ternary operator short circuit in a defined way
问题描述
如果您具有以下条件:
if (x)
{
y = *x;
}
else
{
y = 0;
}
然后保证可以定义行为,因为我们只能取消引用 x
如果不为0
Then behavior is guaranteed to be defined since we can only dereference x
if it is not 0
可以这样表示吗?
y = (x) ? *x : 0;
这似乎按预期工作(即使使用 -Wpedantic $在g ++上为c $ c>)
This seems to work as expected (even compiled with -Wpedantic
on g++)
可以保证吗?
推荐答案
是的,将只计算第二个或第三个操作数,C ++标准草案草稿 5.16
[expr.cond] 说:
Yes, only the second or third operand will be evaluated, the draft C++ standard section 5.16
[expr.cond] says:
条件表达式组从右到左。第一个表达式在上下文中转换为bool(第4条)。
求值,如果为true,则条件表达式的结果为第二个表达式的值,否则为
,第三个表达式的值。 仅计算第二个和第三个表达式中的一个。与第一个表达式相关的每个值
计算和副作用在与第二个表达式相关的每个值计算
和副作用之前进行排序或第三个表达式。
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.
这篇关于三元运算符是否以定义的方式短路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!