[英]Why are operators right associative in CShell that are left associative in C?
[英]Why is the conditional operator right associative?
我能理解为什么赋值运算符是正确的关联。 当什么时候
x = 4 + 3
评估后,将4和3相加后再分配给x。
我不清楚?:
如何从正确的联想中受益。 这样仅使用两个时才有意义?:
z = (a == b ? a : b ? c : d);
然后按以下方式进行评估:
z = (a == b ? a : (b ? c : d));
从左到右进行评估肯定会更有意义吗?
如果从左到右求值,则看起来像这样:
z = ((a == b ? a : b) ? c : d);
也就是说,它将使用第一个条件( a
或b
)的结果作为第二个条件的布尔条件。 那没有什么意义:就像说:
int z, tmp;
/* first conditional */
if(a == b) tmp = a;
else tmp = b;
/* second conditional */
if(tmp) z = c;
else z = d;
也许有一天您可能会想做一件事,但是后面的每个?:
后面的意思是要添加更多条件,例如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;
在具有正确的关联三元运算符的任何语言中,都可以将它们堆叠并构建if-elseif-elseif-else表达式,如下所示:
val = a == 0 ? 1:
a == 1 ? 2:
4;
相反,在具有左关联三元运算符的语言(例如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.
?>
您误解了关联性的概念。
当运算符+
被称为左缔合时,这意味着a + b + c
等于(a + b) + c
,而不是a + (b + c)
。
运算符=
是右关联的,这意味着a = b = c
等于a = (b = c)
,而不是(a = b) = c
。
关联性与评估顺序无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.