12

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

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

3 Answers3

20

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
7

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

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
6

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.

Gopi
  • 19,784
  • 4
  • 24
  • 36