C ++如果条件运算符是左关联的

时间:2013-07-19 10:01:38

标签: c++ conditional-operator

这个问题我发现我真的不知道答案。假设我们有以下代码:

int grade = 100;
string finalgrade = (grade > 90) ? "High Pass"
                                 : (grade > 75) ? "Pass"
                                                : (grade >= 60) ? "low pass" : "fail";

如果条件运算符是左关联的,它将如何评估?

2 个答案:

答案 0 :(得分:2)

如果?:是左关联的,那就意味着:

a ? b : c ? d : e

相当于:

(a ? b : c) ? d : e

而不是:

a ? b : (c ? d : e)

将此应用于您的示例,您将获得:

string finalgrade =   (  (  (grade > 90)
                          ? "High Pass"
                          : (grade > 75))
                       ? "Pass"
                       : (grade >= 60))
                    ? "low pass"
                    : "fail";

- 假设编译器没有抱怨不匹配的类型 - 对于grade = 100会导致:

string finalgrade =   (  (  true
                          ? "High Pass"
                          : (grade > 75))
                       ? "Pass"
                       : (grade >= 60))
                    ? "low pass"
                    : "fail";

string finalgrade =   (  "High Pass"
                       ? "Pass"
                       : (grade >= 60))
                    ? "low pass"
                    : "fail";

string finalgrade =   "Pass"
                    ? "low pass"
                    : "fail";

string finalgrade = "low pass";

答案 1 :(得分:0)

在你的例子中

: finalgrade =“高通”

计算是从右到左完成的