8

I just stumbled upon the following pair of C++ grammar rules:

conditional-expression:
    logical-or-expression
    logical-or-expression ? expression : assignment-expression
                                         ^^^^^^^^^^^^^^^^^^^^^
assignment-expression:
    conditional-expression
    ^^^^^^^^^^^^^^^^^^^^^^
    unary-expression assignment-operator assignment-expression
    throw assignment-expression_opt

Note how the rules are mutually recursive: conditional-expression refers to assignment-expression (rule 2), and assignment-expression refers to conditional-expression (rule 1).

What does this mean with respect to operator precedence? Normally, the non-terminal for the stronger-binding operator occurs on the right-hand side of the rules for the weaker-binding operator, but not the other way around, right? Here is what puzzles me, specifically:

On the one hand, a = b ? c : d means a = (b ? c : d), suggesting ?: binds stronger.

On the other hand, a ? b : c = d means a ? b : (c = d), suggesting = binds stronger.

Does the concept of operator precedence in the traditional sense simply not apply here? Why?

3
  • 2
    en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B "A precedence table, while mostly adequate, cannot resolve a few details. In particular, note that the ternary operator allows any arbitrary expression as its middle operand, despite being listed as having higher precedence than the assignment and comma operators. Thus a ? b , c : d is interpreted as a ? (b, c) : d, and not as the meaningless (a ? b), (c : d). Also, note that the immediate, unparenthesized result of a C cast expression cannot be the operand of sizeof." But that's referring to a different edge case. Commented Mar 27, 2015 at 22:16
  • Wikipedia also notes that in C it's described as logical-OR-expression ? expression : conditional-expression, different than C++ Commented Mar 27, 2015 at 22:26
  • @MooingDuck Oh, that comma thing is interesting! Commented Mar 27, 2015 at 22:27

1 Answer 1

6

?: and = have the same operator precedence, and bind right-to-left.

See cppreference.

1
  • Interesting. I guess I was thrown off by the fact that other resources like this one claim that ?: binds tighter than =. Commented Mar 27, 2015 at 22:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.