2

my code is:

#include<stdio.h>
int main() {
   int a=10, b;
   a >= 5 ? b=100 : b=200;
   printf("%d %d", a, b);
   return 0;
}

Here comes a "Lvalue Required" in the line of conditional operator.

Can you explain me why?

By the way, the same program is perfectly working in C++.

Himanshu Aggarwal
  • 1,763
  • 1
  • 23
  • 35

2 Answers2

7

The idiomatic way to write that assignment is:

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

If you insist on keeping it your way, add parentheses:

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

For details on why this works in C++ but not in C, see Conditional operator differences between C and C++ (thanks @Grijesh Chauhan!)

Community
  • 1
  • 1
NPE
  • 464,258
  • 100
  • 912
  • 987
  • yes. it is working out with parentheses... but the older one is still working in C++. so why there is an error in C then? – Himanshu Aggarwal Mar 03 '13 at 19:57
  • 1
    @HimanshuAggarwal [**Conditional operator differences between C and C++**](http://stackoverflow.com/questions/1082655/conditional-operator-differences-between-c-and-c) – Grijesh Chauhan Mar 03 '13 at 20:03
1

parenthesis have the higher precedence in C.. U get the warning due to precedence problem.. Try this..

(a >= 5) ? (b = 100) : (b = 200);
Raghu Srikanth Reddy
  • 2,673
  • 33
  • 28
  • 41