另一个条件运算符嵌套问题 [英] Yet Another Conditional Operator Nesting Question

查看:91
本文介绍了另一个条件运算符嵌套问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据C优先级表,三元条件运算符具有从右到左的
关联性。

As per C precedence tables, the ternary conditional operator has right-to-left associativity.

因此,如果-else阶梯?

So, is it directly convertible to the equivalent if-else ladder?

例如,可以:

x?y?z:u:v;

应解释为:

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

通过匹配else()最接近的未配对if()?还是从右到左的关联性暗示其他安排?

by matching an else (:) with the closest unpaired if (?)? Or does right-to-left associativity imply some other arrangement?

推荐答案

您给出的示例只能以一种方式解释(就像您给出的if语句),三元运算符是从右到左还是从左到右的关联性。

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;

哪个解释为: x = a? b:(c?d:e),而不是 x =(a?b:c)? d:e

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

举一个更现实的例子:

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

这与if / else-if语句(可能更具可读性)相同:

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;
}

这篇关于另一个条件运算符嵌套问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆