Another conditional statement, nested question

According to the priority tables C, the ternary conditional operator has the right to left associativity.

So, does it directly convert to the equivalent if-else ladder?

For example, Maybe:

x?y?z:u:v;

just interpreted as:

if(x)
{
   if(y)
   { z; }
   else
   { u; }
}
else
{ v; }

matching else (:) with the nearest unpaired if (?)? Or does associativity from right to left imply some other arrangement?

+5
source share
2 answers

The example you gave can only be interpreted in one way (for example, using if statements) whether the triple operator has right-to-left or left-to-right right-handedness.

If a right-to-left relationship matters when you have:

x = a ? b : c ? d : e;

: x = a ? b : (c ? d : e), x = (a ? b : c) ? d : e.

:

int getSign(int x) {
    return x<0 ? -1 :
           x>0 ?  1 :
                  0;
}

(, ) if/else-if:

int getSign(int x) {
    if (x<0)
        return -1;
    else if (x>0)
        return 1;
    else
        return 0;
}
+14

; , :

x?(y?z:u):v
+5

All Articles