Search code examples
c++cassignment-operatorconditional-operatorassociativity

ternary operator and assignment operator


in Does the C/C++ ternary operator actually have the same precedence as assignment operators?

Luchian Grigore's answer says that cases like

a ? b : c = d

will always be inferred as

a ? b : ( c = d )

because both = and ?: associate right to left so

in c++

k =  21 > 3 ? j = 12 : j = 10;

and

k = 1 > 3 ? j = 12 : j = 10;

both are fine.

In C

k = 21 > 3 ? 12 : j = 10

returns error

invalid lvalue in assignment.

Shouldn't above be inferred as (and return no error)

k=  21 > 3 ? 12 : ( j = 10 )

I assume now it is being grouped as

k = ( 21 > 3 ? 12 : j ) = 10

which gives error since in C(not in C++) ternary operator cannot return lvalue. Can anyone tell me exactly how operators are grouped in this case.


Solution

  • Your linked question's (Does the C/C++ ternary operator actually have the same precedence as assignment operators?) answer by @hvd shows the answer.

    The C++ and C grammars for ?: are different.

    In C++, the rightmost operand is allowed to be an assignment expression (so the compiler [greedily] treats the = are part of the ?:) while in C the rightmost operand is a conditional-expression instead. Thus in C as soon as the compiler hits the = the analysis of ?: is complete and it treats it as k = ( 21 > 3 ? 12 : j ) = 10.