Ternary operator in C vs C ++

There are many differences between C and C ++ and you had to get stuck on one of them. The same code gives an error in C, but just performs fine in C ++ Please explain the reason

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

The above code shows an error in C indicating lvalue if the same code compiles in C ++

+6
source share
3 answers

Look at the priority of the operator.

Without explicit () your code behaves like

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

The result of the expression ?: not a mutable value of l [#] and, therefore, we cannot assign any values ​​to it.

Also worth mentioning, according to the c syntax rule,

never allowed to appear on the right side of a conditional statement

Background: Priority Table C.

OTOH, In the case of c++ , well,

the conditional statement has the same priority as the assignment.

and grouped from right to left, essentially making your code the same as

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

So your code works fine in case of c++


[#] - according to chapter 6.5.15, footnote (12), C99 standard,

The conditional expression does not give an lvalue.

+16
source

Because C and C ++ are not the same language, and you are ignoring the purpose implied by the triple. I think you wanted

 b = a>=5?100:200; 

which should work both in C and C ++.

+6
source

In C, you can fix this by placing the expression in parentheses so that when you evaluate the assignment, it becomes valid.

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

The error occurs because you do not care about the priority and order of evaluation of the operator.

+5
source

Source: https://habr.com/ru/post/982016/


All Articles