[Solved] lvalue required as left operand of assignment

Previous

In this post, we will see how to solve lvalue required as left operand of assignment in C or C++.

Let’s first understand first about the error.

When you are using assignment operator(=) in a statement, then LHS of assignment operator must be something called lvalue, Otherwise you will get this error.

If LHS does not evaluate to lValue, then you can not assign RHS to LHS.

5 = 10

since 5 does not evaluate to lvalue, you can not assign 10 to it. This is invalid assignment.

int a;
a = 5;

since a will be evaluated to lvalue.

but you can not use

a + 1 =5;

since a + 1 can not evaluated to lvalue, you can not assign value like this.

Let’s understand few common use cases for this error.


Scenario 1

You want to write a program to check if number is odd or even.

You will get compilation error with below message.

main.c: In function ‘main’:
main.c:14:19: error: lvalue required as left operand of assignment
if(number % 2 = 0)
^

Did you get the error, we have put = instead of == to check equality with 0.
Solution:
Change highlighted line
if(number % 2 = 0)
to
if(number % 2 == 0)
and above program should work fine.


Scenario 2

Let’s say you have program as below:

You will get compilation error with below message.

main.c: In function ‘main’:
main.c:14:16: error: lvalue required as left operand of assignment
number + 1 = 20;
^

number + 1 won’t be evaluated to lvalue, hence you are getting above error.
Solution:
Change highlighted line
number + 1 = 20;
to
number = 20;
and above program should work fine.


Scenario 3

Let’s say you have program as below:

You will get compilation error with below message.

main.c: In function ‘main’:
main.c:13:22: error: lvalue required as left operand of assignment
a<=100? b=20 : c=40;

Solution:
We are getting this error because conditional operator has higher precedence than assignment operator so highlighted line will be treated as
((a<=100 ? (b=20) : c) = 40;
You can put parenthethis to solve this problem
(a<=100 ? (b=20) : (c = 40);
and above program should work fine.
[c mark=”5″]
#include
int main()
{
int a = 40 ,b,c;
(a<=100) ? (b=20) : (c = 40); printf("value of b is : %d ",b); return 0; }/c] Output:

value of b is : 20

That’s all about how to solve lvalue required as left operand of assignment in C/C++.

Previous

Add Comment