Table of Contents
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.
since 5 does not evaluate to lvalue, you can not assign 10 to it. This is invalid assignment.
a = 5;
since a will be evaluated to lvalue.
but you can not use
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <stdio.h> int main() { int number =10 ; // True if the number is perfectly divisible by 2 if(number % 2 = 0) printf("%d is even.", number); else printf("%d is odd.", number); return 0; } |
You will get compilation error with below message.
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:
1 2 3 4 5 6 7 8 9 |
#include <stdio.h> int main() { int number = 10 ; number + 1 = 20; return 0; } |
You will get compilation error with below message.
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:
1 2 3 4 5 6 7 8 9 10 |
#include <stdio.h> int main() { int a=40 ,b,c; a<=100 ? b=20 : c=40; printf("value of b is : %d ",b); return 0; } |
You will get compilation error with below message.
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:
That’s all about how to solve lvalue required as left operand of assignment in C/C++.