Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include <stdio.h>
int main()
{
int b,i=5;
i==5?b=2:b=4;
printf ("%d",b);
return 0;
}

Syntax error: lvalue required

What I have tried:

The issue gets resolved on using brackets (b=2) & (b=4). I found the answer on internet. But i don't know the reason. Please tell me the reason for it.
Thanks.
Posted
Updated 16-Aug-18 2:25am

1 solution

Operator precedence is the problem:
i == 5 ? (b = 2) : (b = 4);
But that is very badly written, and does little of any use.
Instead, try this:
b = i == 5 ? 2 : 4;

which does the same thing by a lot more readably!
 
Share this answer
 
Comments
Member 13922884 16-Aug-18 8:28am    
Ok Thankyou !!
OriginalGriff 16-Aug-18 8:34am    
You're welcome!
Member 13922884 16-Aug-18 10:05am    
b=i==5?2:4; is comprehensible to me. First ternary operator was evaluated and then its value was passed to b.

But how does putting brackets help in the above statement?
Ternary operator have higher precedence than assignment operator,i know. But is b=7 not equal to (b=7).
OriginalGriff 16-Aug-18 10:22am    
Because the compiler sees your version as this:
(i==5?b)=(2:b)=4;>/pre>
And goes "Eh? You what? That isn't an LValue!"
The left hand side of <code>a = b </code> must be an LValue - a value that can be assigned to, not a constant, or a result.
Member 13922884 16-Aug-18 12:23pm    
Ok. Thanks again.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900