1

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.

melpomene
  • 84,125
  • 8
  • 85
  • 148
gigi
  • 669
  • 6
  • 11

3 Answers3

2

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.)

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • "Operator associativity has nothing to do with what is executed first." But in `(a @ b) @ c` then surely `a @ b` is executed first, instead of `b @ c` ? – artm Jan 08 '17 at 00:41
  • 1
    @artm Consider `(f() @ g()) @ h()`. You don't know which function is called first. By my statement I was referring to the execution of `a`, `b`, and `c`. – melpomene Jan 08 '17 at 00:43
  • 1
    @artm Even then, consider `a && (b && c)`. In C++ `b && c` can't be executed first because if `a` is `false`, the first `&&` returns `false` immediately. – melpomene Jan 08 '17 at 00:44
  • I think without that statement it would be clearer.. I like the part that simply explains what left (and right) associativity mean – artm Jan 08 '17 at 00:45
1

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");
Peter
  • 35,646
  • 4
  • 32
  • 74
0

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".

4Dimensions
  • 83
  • 1
  • 10