Jun 6, 2014 at 6:31pm Jun 6, 2014 at 6:31pm UTC
I don't understand the error which the following program gives on compilation.
1 2 3
int a = 10,b;
a >= 5 ? b = 100 : b= 200;
printf("%d\n" ,b);
The error is "lvalue required as left operand of assignment"
Last edited on Jun 6, 2014 at 6:31pm Jun 6, 2014 at 6:31pm UTC
Jun 6, 2014 at 6:34pm Jun 6, 2014 at 6:34pm UTC
Try using brackets:
int a = 10,b;
(a >= 5) ? b = 100 : b= 200;
printf("%d\n",b);
Jun 6, 2014 at 6:34pm Jun 6, 2014 at 6:34pm UTC
I understand that, but i want to know the reason why this error occurs, or what it means.
Last edited on Jun 6, 2014 at 6:35pm Jun 6, 2014 at 6:35pm UTC
Jun 6, 2014 at 6:37pm Jun 6, 2014 at 6:37pm UTC
I think it may be because your compiler is misunderstanding the order of operations, so gets confused
Jun 6, 2014 at 7:17pm Jun 6, 2014 at 7:17pm UTC
In C, the ternary operator has a higher priority than = and your code is parsed thusly:
(a >= 5 ? b = 100 : b) = 200 ;
In C++ it will work as expected since both operators have the same priority.