简体   繁体   English

C 中三元运算符的求值顺序

[英]Order of evaluation for ternary operator in C

I am aware that according to the standard, fun(++a, a) should be avoided since second argument is not well defined.我知道根据标准, fun(++a, a)应该避免,因为第二个参数没有很好地定义。

However, is this formulation safe:但是,这种配方是否安全:

(++a ? a : 10);

I tested this snippet and it works as expected, ie for a = -1 it evaluates as 10 , and for any other a it evaluates as a+1 .我测试了这个片段,它按预期工作,对于a = -1它评估为10 ,对于任何其他a它评估为a+1 Is this well defined in the standard, or it strongly depends on the compiler?这是在标准中明确定义的,还是强烈依赖于编译器?

This is well defined.这是很好定义的。

In a ternary expression, the first part is evaluated first.在三元表达式中,首先计算第一部分。 Then based on that value, either the second or the third part is evaluated.然后根据该值,评估第二部分第三部分。 So ++a is guaranteed to be evaluated before a is possible evaluated.所以++a保证在a可能被评估之前被评估。

This is explained in section 6.5.15p4 of the C standard : C 标准的第 6.5.15p4 节对此进行了解释:

The first operand is evaluated;评估第一个操作数; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated) .在它的求值和第二个或第三个操作数的求值之间有一个序列点(以求值者为准) The second operand is evaluated only if the first compares unequal to 0;仅当第一个比较不等于 0 时才计算第二个操作数; the third operand is evaluated only if the first compares equal to 0;仅当第一个比较等于 0 时才评估第三个操作数; the result is the value of the second or third operand(whichever is evaluated), converted to the type described below.结果是第二个或第三个操作数的值(以评估的为准),转换为下面描述的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM