[英]Why is the conditional operator right associative?
I can understand why the assignment operator is right associative. 我能理解为什么赋值运算符是正确的关联。 It makes sense that when 当什么时候
x = 4 + 3
is evaluated, that 4 and 3 are added before being assigned to x. 评估后,将4和3相加后再分配给x。
I am unclear as to how ?:
would benefit from being right associative. 我不清楚?:
如何从正确的联想中受益。 Does it only matter when two ?:
s were used like this 这样仅使用两个时才有意义?:
z = (a == b ? a : b ? c : d);
Then it is evaluated like this: 然后按以下方式进行评估:
z = (a == b ? a : (b ? c : d));
Surely it would make more sense to evaluate from left to right? 从左到右进行评估肯定会更有意义吗?
If it evaluated from left to right, it'd look like this: 如果从左到右求值,则看起来像这样:
z = ((a == b ? a : b) ? c : d);
That is, it would use the result of the first conditional ( a
or b
) as the boolean condition of the second conditional. 也就是说,它将使用第一个条件( a
或b
)的结果作为第二个条件的布尔条件。 That doesn't make much sense: that's like saying: 那没有什么意义:就像说:
int z, tmp;
/* first conditional */
if(a == b) tmp = a;
else tmp = b;
/* second conditional */
if(tmp) z = c;
else z = d;
While perhaps one day you'll want to do exactly this, it's far more likely that each ?:
that follows is meant to add more conditions, like if
/ else if
/ else if
/ else
, which is what the right-associative binding yields: 也许有一天您可能会想做一件事,但是后面的每个?:
后面的意思是要添加更多条件,例如if
/ else if
/ else if
/ else
,这就是右关联绑定产生的结果:
int z;
/* first conditional */
if(a == b) z = a;
else /* second conditional */ if(b) z = c;
else z = d;
In any language with a right associative ternary operator, you can stack them and build an if-elseif-elseif-else expression, like this: 在具有正确的关联三元运算符的任何语言中,都可以将它们堆叠并构建if-elseif-elseif-else表达式,如下所示:
val = a == 0 ? 1:
a == 1 ? 2:
4;
On the contrary, in languages with a left associative ternary operator (such as PHP, thanks @user786653) you need to explicitly enforce the aforementioned intent with parentheses: 相反,在具有左关联三元运算符的语言(例如PHP,感谢@ user786653)中,您需要使用括号显式地强制执行上述意图:
<?php
// This will output 't', not 'true'.
echo (true ? 'true' : false ? 't' : 'f');
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
You got the concept of associativity wrong. 您误解了关联性的概念。
When operator +
is said to be left-associative, this means that a + b + c
is equivalent to (a + b) + c
, as opposed to a + (b + c)
. 当运算符+
被称为左缔合时,这意味着a + b + c
等于(a + b) + c
,而不是a + (b + c)
。
The operator =
is right-associative, which means that a = b = c
is equivalent to a = (b = c)
, as opposed to (a = b) = c
. 运算符=
是右关联的,这意味着a = b = c
等于a = (b = c)
,而不是(a = b) = c
。
Associativity has nothing to do with the order of evaluation. 关联性与评估顺序无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.