Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does assignment or conditional bind stronger?

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?

like image 250
fredoverflow Avatar asked Mar 27 '15 22:03

fredoverflow


1 Answers

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

See cppreference.

like image 189
orlp Avatar answered Oct 19 '22 18:10

orlp