为什么条件运算符是正确关联的?

Ang*_*ber 35 c conditional-operator

我可以理解为什么赋值运算符是正确关联的.什么时候才有意义

x = 4 + 3
Run Code Online (Sandbox Code Playgroud)

评估,在分配给x之前添加4和3.

我不清楚如何?:从正确的联想中获益.只有两个?:人像这样使用才有意义

z = (a == b ? a : b ? c : d);
Run Code Online (Sandbox Code Playgroud)

然后它被评估如下:

z = (a == b ? a : (b ? c : d));
Run Code Online (Sandbox Code Playgroud)

从左到右进行评估肯定会更有意义吗?

Chr*_*utz 41

如果从左到右进行评估,它看起来像这样:

z = ((a == b ? a : b) ? c : d);
Run Code Online (Sandbox Code Playgroud)

也就是说,它将使用第一个条件(ab)的结果作为第二个条件的布尔条件.这没有多大意义:那就像说:

int z, tmp;
/* first conditional */
if(a == b) tmp = a;
else       tmp = b;
/* second conditional */
if(tmp) z = c;
else    z = d;
Run Code Online (Sandbox Code Playgroud)

虽然也许有一天你会想要做到这一点,但后面的每一个更有可能?:是添加更多条件,比如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;
Run Code Online (Sandbox Code Playgroud)


Mic*_*kis 20

在具有右关联三元运算符的任何语言中,您可以堆叠它们并构建if-elseif-elseif-else表达式,如下所示:

val = a == 0 ? 1:
      a == 1 ? 2:
               4;
Run Code Online (Sandbox Code Playgroud)

相反,在具有左关联三元运算符的语言中(例如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.
?>
Run Code Online (Sandbox Code Playgroud)

  • 偏离主题,但我无法拒绝链接到[PHP手册](http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary)*left*associative三元运算符的示例. (13认同)
  • 我会说这完全是主题.问题是*为什么*条件运算符是右关联的(尽管OP可能不太明白这意味着什么).PHP示例显示了将条件运算符定义为左关联的缺点. (8认同)

Rol*_*lig 5

你弄错了关联性的概念。

当运算符+被称为左结合时,这意味着它a + b + c等价于(a + b) + c,而不是a + (b + c)

运算符=是右结合的,这意味着a = b = c相当于a = (b = c),而不是(a = b) = c

结合性与求值顺序无关。

  • “关联性与评估顺序无关。” 好吧,除非所有运算符都具有相同的优先级。 (4认同)
  • 我指的是在分配给 x* 之前添加了 *4 和 3。先计算运算符的右手边还是左手边,与结合性无关。并且无论运算符是右结合还是左结合,操作数必须始终在*执行实际操作之前*进行评估。 (3认同)
  • @Keith - 我的大脑在别处。我仍然不明白为什么这个答案开始讨论评估顺序,但是当我读到时,我显然没有考虑“评估顺序”实际上是什么。 (2认同)