As per C precedence tables, the ternary conditional operator has right-to-left
associativity.
So, is it directly convertible to the equivalent if-else ladder?
For example, can:
x?y?z:u:v;
be interpreted as:
if(x)
{
if(y)
{ z; }
else
{ u; }
}
else
{ v; }
by matching an else (:) with the closest unpaired if (?)? Or does right-to-left associativity imply some other arrangement?
The example you gave could only be interpreted in one way (like the if statements you gave), whether the ternary operator had right-to-left or left-to-right associativity.
Where the right-to-left associativity matters is when you have:
Which is interpreted as:
x = a ? b : (c ? d : e), not asx = (a ? b : c) ? d : e.To give a more realistic example:
This is identical to the (probably more readable) if / else-if statements: