Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

c - 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.

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?

question from:https://stackoverflow.com/questions/7407273/why-is-the-conditional-operator-right-associative

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. 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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...