Ternary operator in C vs C++ [duplicate]

与世无争的帅哥 提交于 2019-12-03 12:38:44

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.

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

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.

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