Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 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 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...