C++ 嵌套条件运算符的求值顺序
C++ nested conditional operator order of evaluation
对于像
这样的表达式
x = a ? b : c ? d : e;
我理解因为 ?: 运算符具有右结合性,所以表达式被分组为
x = a ? b : (c ? d : e);
但是,评估的顺序呢?结合性是否意味着 (c ? d : e) 分支首先求值,然后它的答案作为参数传递给左边的 ?: 运算符?还是先评估 a,然后根据返回 b 或评估 (c ? d : e) 分支?还是未定义?
对于条件运算符:
- 首先计算第一个操作数;
- 根据第一个的值评估第二个或第三个(但不是两者)。
Naht K.16/1
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.
对于像
这样的表达式x = a ? b : c ? d : e;
我理解因为 ?: 运算符具有右结合性,所以表达式被分组为
x = a ? b : (c ? d : e);
但是,评估的顺序呢?结合性是否意味着 (c ? d : e) 分支首先求值,然后它的答案作为参数传递给左边的 ?: 运算符?还是先评估 a,然后根据返回 b 或评估 (c ? d : e) 分支?还是未定义?
对于条件运算符:
- 首先计算第一个操作数;
- 根据第一个的值评估第二个或第三个(但不是两者)。
Naht K.16/1
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.