Ternary operator in C vs C++ [duplicate]

2019-03-27 15:06发布

This question already has an answer here:

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

3条回答
做自己的国王
2楼-- · 2019-03-27 15:38

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

查看更多
Juvenile、少年°
3楼-- · 2019-03-27 15: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.

查看更多
干净又极端
4楼-- · 2019-03-27 15:45

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.

查看更多
登录 后发表回答