C++, conditional operator associativity

237 views Asked by At

in this code :

finalgrade = (grade > 90) ? "high pass" : (grade < 60) ? "fail" : "pass";

A book says the the ?: operator is right associative. I did an internet search so I understand what associativity means. But I can't really understand what it means for the code above. C++ starts by doing what? This operation should be left associative because it should start in the left, doing the first condition, and continue by doing the second condition if necessary, not the other way around.

3

There are 3 answers

0
Peter On BEST ANSWER

If ?: was left associative, the statement

finalgrade = (grade > 90) ? "high pass" : (grade < 60) ? "fail" : "pass";

would be treated as

finalgrade = ((grade > 90) ? "high pass" : (grade < 60)) ? "fail" : "pass";

which (in this case) would not compile, since "high pass" and (grade < 60) have different types.

Since it is actually right associative, the statement is treated as

finalgrade = (grade > 90) ? "high pass" : ((grade < 60) ? "fail" : "pass");
0
4Dimensions On

This pretty much translates to:

Is my final grade's mark above 90? If so it's considered a high pass. Else is it below 60? If so it's considered a fail. And then if the results are anything other than above 90 or below 60, it's just considered a "pass".

4
melpomene On

Operator associativity has nothing to do with what is executed first. If you have an operator @, associativity tells you whether

a @ b @ c

should be read as

(a @ b) @ c

or

a @ (b @ c)

In your case, ? ... : works like a right-associative operator:

(grade > 90) ? "high pass" : (grade < 60) ? "fail" : "pass"

parses as

(grade > 90) ? "high pass" : ((grade < 60) ? "fail" : "pass")

In other words, the "else branch" of the first ?: contains another nested ?:.

(If it were left associative, it would be

((grade > 90) ? "high pass" : (grade < 60)) ? "fail" : "pass"

, which makes little sense.)