ternary operator and assignment operator

天涯浪子 提交于 2019-12-10 21:11:19

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/17406503/ternary-operator-and-assignment-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!