Zxcv Mnb
Zxcv Mnb

Reputation: 743

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.

Upvotes: 5

Views: 8243

Answers (2)

Mark B
Mark B

Reputation: 96241

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.

Upvotes: 2

unxnut
unxnut

Reputation: 8839

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

if ( 21 > 3 )
    k = 12;
else
    k = ( j = 10 );

Since 21>3 is true, the else condition does not get evaluated and j has undefined value (or whatever value it had prior to this statement).

Upvotes: 0

Related Questions