Yet Another Conditional Operator Nesting Question

拥有回忆 提交于 2020-01-11 02:49:08

问题


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?


回答1:


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:

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

Which is interpreted as: x = a ? b : (c ? d : e), not as x = (a ? b : c) ? d : e.

To give a more realistic example:

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

This is identical to the (probably more readable) if / else-if statements:

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



回答2:


Your assumption is correct; however, it is often wise to add in parentheses for readability, e.g.:

x ? ( y ? z : u ) : v


来源:https://stackoverflow.com/questions/4770506/yet-another-conditional-operator-nesting-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!