Ternary operator in C vs C++ [duplicate]

痞子三分冷 提交于 2019-12-12 07:50:37

问题


There are a lot of differences between C and C++ and came to stuck on one of them The same code gives an error in C while just executes fine in C++ Please explain the reason

int main(void)
{
   int a=10,b;
   a>=5?b=100:b=200;
}

The above code gives an error in C stating lvalue required while the same code compiles fine in C++


回答1:


Have a look at the operator precedence.

Without an explicit () your code behaves like

( a >= 5 ? b = 100 :  b ) = 200;

The result of a ?: expression is not a modifiable lvalue [#] and hence we cannot assign any values to it.

Also, worthy to mention, as per the c syntax rule,

assignment is never allowed to appear on the right hand side of a conditional operator

Relared Reference : C precedence table.

OTOH, In case of c++, well,

the conditional operator has the same precedence as assignment.

and are grouped right-to-left, essentially making your code behave like

 a >= 5 ? (b = 100) : ( b = 200 );

So, your code works fine in case of c++


[ # ] -- As per chapter 6.5.15, footnote (12), C99 standard,

A conditional expression does not yield an lvalue.




回答2:


Because C and C++ aren't the same language, and you are ignoring the assignment implied by the ternary. I think you wanted

b = a>=5?100:200;

which should work in both C and C++.




回答3:


In C you can fix it with placing the expression within Parentheses so that while evaluating the assignment becomes valid.

int main(void)
{
   int a=10,b;
   a>=5?(b=100):(b=200);
}

The error is because you don't care about the operator precedence and order of evaluation.



来源:https://stackoverflow.com/questions/28337054/ternary-operator-in-c-vs-c

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