c++ - 三元运算符是否以定义的方式短路

标签 c++ undefined-behavior conditional-operator short-circuiting

如果您有以下情况:

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

因为我们只能取消引用 x 如果它不是 0

那么行为就可以保证被定义

也可以这样说:

y = (x) ? *x : 0;

这似乎按预期工作(甚至在 g++ 上用 -Wpedantic 编译)

这是有保证的吗?

最佳答案

是的,只有第二个或第三个操作数会被评估,C++ 标准草案部分 5.16 [expr.cond] 说:

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.

关于c++ - 三元运算符是否以定义的方式短路,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33417436/

相关文章:

c# - 从 C++ 回调到 C#

c++ - 从文件c++中将单个字符读入变量

c - 以下使用涉及越界访问的指针算法的语句是否有效?

c++ - 将不相关类型的对象重新解释为空类是否是未定义行为

mysql - 在 Mysql 查询中使用 IF

php - 什么是 ? : in PHP 5. 3?

C++ 字符串继承

c++ - 用户空间和内核空间进程中的一组信号处理程序

c++ - 未定义的行为是否会在定义为从不抛出异常的函数中导致异常?

JavaScript 嵌套三元运算符