Why is the conditional operator right associative?

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;

Leave a Comment