为什么条件运算符右结合? [英] Why is the conditional operator right associative?

查看:247
本文介绍了为什么条件运算符右结合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以理解为什么赋值运算符是右结合。这是有道理的,当

I can understand why the assignment operator is right associative. It makes sense that when

x = 4 + 3

进行评价,即4和3加到被分配到X之前

is evaluated, that 4 and 3 are added before being assigned to 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);

也就是说,它将使用第一个条件( A B )作为布尔条件的结果的第二条件。这并没有多大意义:这等于是说:

That is, it would use the result of the first conditional (a or b) as the boolean condition of the second conditional. 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:

int z;
/* first conditional */
if(a == b)                          z = a;
else /* second conditional */ if(b) z = c;
else                                z = d;

这篇关于为什么条件运算符右结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆