[英]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.