Ошибка lvalue required as left operand of assignment

You need to compare, not assign:

if (strcmp("hello", "hello") == 0)
                             ^

Because you want to check if the result of strcmp("hello", "hello") equals to 0.

About the error:

lvalue required as left operand of
assignment

lvalue means an assignable value (variable), and in assignment the left value to the = has to be lvalue (pretty clear).

Both function results and constants are not assignable (rvalues), so they are rvalues. so the order doesn’t matter and if you forget to use == you will get this error. (edit:)I consider it a good practice in comparison to put the constant in the left side, so if you write = instead of ==, you will get a compilation error. for example:

int a = 5;
if (a = 0) // Always evaluated as false, no error.
{
    //...
}

vs.

int a = 5;
if (0 = a) // Generates compilation error, you cannot assign a to 0 (rvalue)
{
    //...
}

(see first answer to this question: https://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined)

The message “error: lvalue required as left operand of assignment” can be shown quite frequently when you write your C/C++ programs. Check out the explanation below to understand why it happens.

l-values And r-values

In C and C++, we can put expressions into many categories, including l-values and r-values

The history of these concepts can be traced back to Combined Programming Language. Their names are derived from the sides where they are typically located on an assignment statement.

Recent standards like C++17 actually define several categories like xvalue or prvalue. But the definitions of l-values and r-values are basically the same in all C and C++ standards.

In simple terms, l-values are memory addresses that C/C++ programs can access programmatically. Common examples include constants, variable names, class members, unions, bit-fields, and array elements.

In an assignment statement, the operand on the left-hand side should be a modifiable l-value because the operator will evaluate the right operand and assign its result to the left operand.

This example illustrates the common correct usage of l-values and r-values:

int main() {
   int x, *p;
   x = 4;
   x++;
   *p = x;
   return 0;
}

In the ‘x = 4’ statement, x is an l-value while the literal 4 is not. The increment operator also requires an l-value because it needs to read the operand value and modify it accordingly.

Similarly, dereferenced pointers like *p are also l-values. Notice that an l-value (like x) can be on the right side of the assignment statement as well.

Causes And Solutions For “error: lvalue required as left operand of assignment”

C/C++ compilers generates this error when you don’t provide a valid l-value to the left-hand side operand of an assignment statement. There are many cases you can make this mistake.

Example 1

This code can’t be compiled successfully:

#include <iostream>
using namespace std;
int main() {
   int x;
   4 = x;
   cout << x;
   return 0;
}

Output:

example1.cpp: In function ‘int main()’:
example1.cpp:6:4: error: lvalue required as left operand of assignment
    6 |    4 = x;
      |    ^

As we have mentioned, the number literal 4 isn’t an l-value, which is required for the left operand. You will need to write the assignment statement the other way around:

#include <iostream>
using namespace std;
int main() {
   int x;
   x = 4;
   cout << x;
   return 0;
}

Output:

4

Example 2

In the same manner, this program won’t compile either:

int main() {
   int x;
   x = 4;
   x + 1 = x;
   cout << x;
   return 0;
}

In C/C++, the ‘x + 1’ expression doesn’t evaluate to a l-value. You can fix it by switching the sides of the operands:

int main() {
   int x;
   x = 4;
   x = x + 1;
   cout << x;
   return 0;
}

Output:

5

Example 3

This is another scenario the compiler will complain about the left operand:

int main() {
   int x;
   (-x) = 4;
   cout << x;
   return 0;
}

(-x) doesn’t evaluate to a l-value in C/C++, while ‘x’ does. You will need to change both operands to make the statement correct:

int main() {
   int x;
   x = -4;
   cout << x;
   return 0;
}

Output:

-4

Example 4

Many people also use an assignment operator when they need a comparison operator instead:

#include <iostream>
#include <string.h>
using namespace std;
int main() {
   char str1[] = "LearnShareIT";
   char str2[] = "LearnShareIT";
   if (strcmp (str1,str2) = 0) {
      cout << "Two strings are equal.";
   } else {
      cout << "Two strings are not equal.";
   }
   return 0;
}

This leads to a compilation error:

example4.cpp: In function ‘int main()’:
example4.cpp:8:15: error: lvalue required as left operand of assignment
    8 |    if (strcmp (str1,str2) = 0) {
      |        ~~~~~~~^~~~~~~~~~~

The if statement above needs to check the output of a comparison statement:

if (strcmp (str1,str2) == 0)

Output:

Two strings are equal.

Summary

C/C++ compilers will give you the message “error: lvalue required as left operand of assignment” when there is an assignment statement in which the left operand isn’t a modifiable l-value. This is usually the result of syntax misuse. Correct it, and the error should disappear.

Maybe you are interested:

  • Expression preceding parentheses of apparent call must have (pointer-to-) function type
  • ERROR: conditional jump or move depends on the uninitialized value(s)
  • Print a vector in C++

Robert J. Charles

My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.


Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: Java, C#, C, Javascript, R, Typescript, ReactJs, Laravel, SQL, Python

In this tutorial you will know about one of the most occurred error in C and C++ programming, i.e. lvalue required as left operand of assignment.

lvalue means left side value. Particularly it is left side value of an assignment operator.

rvalue means right side value. Particularly it is right side value or expression of an assignment operator.

Example:

In above example is lvalue and b + 5 is rvalue.

In C language lvalue appears mainly at four cases as mentioned below:

  1. Left of assignment operator.
  2. Left of member access (dot) operator (for structure and unions).
  3. Right of address-of operator (except for register and bit field lvalue).
  4. As operand to pre/post increment or decrement for integer lvalues including Boolean and enums.

Now let see some cases where this error occur with code.

Example 1:

#include<stdio.h>

int main(){

    int a =5,b=5;

    if(a%b=0)

        printf(«its crazy»);

    return 0;

}

When you will try to run above code, you will get following error.

lvalue required as left operand of assignment

Solution: In if condition change assignment operator to comparison operator, as shown below.

#include<stdio.h>

int main(){

    int a =5,b=5;

    if(a%b==0)

        printf(«its crazy»);

    return 0;

}

Example 2:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#include<stdio.h>

int findFact(int n){

    int ans=1,i;

    for(i=1;i<=n;i++){

ans*i=ans;

}

return ans;

}

int main(){

int n=5;

int fact=findFact(n);

printf(«%d»,fact);

return 0;

}

Above code will show the error: lvalue required as left operand of assignment operator.

Here problem occurred due to wrong handling of short hand operator (*=) in findFact() function.

Solution: Just by changing the line ans*i=ans to ans*=i we can avoid that error. Here short hand operator expands like this, ans=ans*i. Here left side some variable is there to store result. But in our program ans*i is at left hand side. It’s an expression which produces some result. While using assignment operator we can’t use an expression as lvalue.

The correct code is shown below.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#include<stdio.h>

int findFact(int n){

    int ans=1,i;

    for(i=1;i<=n;i++){

ans*=i;

}

return ans;

}

int main(){

int n=5;

int fact=findFact(n);

printf(«%d»,fact);

return 0;

}

Example 3:

// misunderstanding ternary operator

#include<stdio.h>

int main(){

int a=5,b;

a>=5?b=10:b=19;

return 0;

}

Above code will show the same lvalue required error.

Reason and Solution: Ternary operator produces some result, it never assign values inside operation. It is same as a function which has return type. So there should be something to be assigned but unlike inside operator.

The correct code is given below.

#include<stdio.h>

int main(){

int a=5,b;

b = a>=5? 10: 19;

return 0;

}

Some Precautions To Avoid This Error

There are no particular precautions for this. Just look into your code where problem occurred, like some above cases and modify the code according to that.

Mostly 90% of this error occurs when we do mistake in comparison and assignment operations. When using pointers also we should careful about this error. And there are some rare reasons like short hand operators and ternary operators like above mentioned. We can easily rectify this error by finding the line number in compiler, where it shows error: lvalue required as left operand of assignment.

Programming Assignment Help on Assigncode.com, that provides homework ecxellence in every technical assignment.

Comment below if you have any queries related to above tutorial.

How to fix error lvalue required as left operand of assignmentThe error code that reads lvalue required as left operand of assignment occurs in C-like languages. It happens when the language can not deduce if the left-hand side of a statement is an lvalue or not, thereby causing a frustrating error code to appear.

Keep on reading this guide as our experts teach you the different scenarios that can cause this error and how you can fix it. In addition, we’ll also answer some commonly-asked questions about the lvalue required error.

Contents

  • Why Do You Have the Error Lvalue Required as Left Operand of Assignment?
    • – Misuse of the Assignment Operator
    • – Mishandling of the Multiplication Assignment Operator
    • – Misunderstanding the Ternary Operator
    • – Using Pre-increment on a Temporary Variable
    • – Direct Decrement of a Numeric Literal
    • – Using a Pointer to a Variable Value
    • – Wrong Placement of Expression
  • How To Fix Lvalue Required as Left Operand of Assignment
    • – Use Equality Operator During Comparisons
    • – Use a Counter Variable as the Value of the Multiplication Assignment Operator
    • – Use the Ternary Operator the Right Way
    • – Don’t Pre-increment a Temporary Variable
    • – Use Pointer on a Variable, Not Its Value
    • – Place an Expression on the Right Side
  • Lvalue Required: Common Questions Answered
    • – What Is Meant by Left Operand of Assignment?
    • – What Is Lvalues and Rvalues?
    • – What Is Lvalue in Arduino?
  • Conclusion

Why Do You Have the Error Lvalue Required as Left Operand of Assignment?

The reason you are seeing the lvalue required error is because of several reasons such as: misuse of the assignment operator, mishandling of the multiplication assignment operator, misunderstanding the ternary operator, or using pre-increment on a temporary variable. Direct decrement of a numeric literal, using a pointer to a numeric value, and wrong placement of expression can also cause this error.

The first step to take after receiving such an error is to diagnose the root cause of the problem. As you can see, there are a lot of possible causes as to why this is occurring, so we’ll take a closer look at all of them to see which one fits your experience.

– Misuse of the Assignment Operator

When you misuse the equal sign in your code, you’ll run into the lvalue required error. This occurs when you are trying to check the equality of two variables, so during the check, you might have used the equal sign instead of an equality check. As a result, when you compile the code, you’ll get the lvalue required error.

In the C code below, we aim to check for equality between zero and the result of the remainder between 26 and 13. However, in the check, we used the equal sign on the left hand of the statement. As a result, we get an error when we compare it with the right hand operand.

#include <stdio.h>
// This code will produce an error
int main() {
int a = 26;
int b = 13;
if (a % b = 0) {
printf(“%s”, “It’s all good”);
}
}

– Mishandling of the Multiplication Assignment Operator

Mishandling of the multiplication assignment operator will result in the lvalue required error. This happens if you don’t know how compilers evaluate a multiplication assignment operator. For example, you could write your statement using the following format:

variable * increment = variable

The format of this statement will cause an error because the left side is an expression, and you cannot use an expression as an lvalue. This is synonymous to 20 multiplied by 20 is equal to 20, so the code below is an assignment error.

#include <stdio.h>
int findFactorial(int n) {
int result = 1, i;
for ( i = 1; i <= n; i++) {
result*1 = result; // Here is the error
}
return result;
}
int main() {
int n = 5;
int factorial = findFactorial(n);
printf(“%d”, factorial);
return 0;
}

– Misunderstanding the Ternary Operator

The ternary operator produces a result, it does not assign a value. So an attempt to assign a value will result in an error. Observe the following ternary operator:

(x>y)?y=x:y=y

Many compilers will parse this as the following:

((x>y)?y=x:y)=y

This is an error. That is because the initial ternary operator ((x>y)?y=x:y) results in an expression. That’s what we’ve done in the next code block. As a result, it leads to the error lvalue required as left operand of assignment ternary operator.

#include <stdio.h>
int main() {
int x = 23, y;
x >= 23? y = 4: y = 12;
printf(“%d”, y);
return 0;
}

– Using Pre-increment on a Temporary Variable

An attempt to pre-increment a temporary variable will also lead to an lvalue required error. That is because a temporary variable has a short lifespan, so they tend to hold data that you’ll soon discard. Therefore, trying to increment such a variable will lead to an error.

For example, in the code below, we pre-increment a variable after we decrement it. As a result, it leads to the error lvalue required as increment operand.

#include <stdio.h>
int main() {
int i = 5;
printf(“%dn” ++(-i)); // Error
}

– Direct Decrement of a Numeric Literal

Direct decrement of a numeric literal will lead to an error. That is because in programming, it’s illegal to decrement a numeric literal, so don’t do it, use variables instead. We’ll show you a code example so you’ll know what to avoid in your code.

In our next code block, we aim to reduce the value of X and Y variables. However, decrementing the variables directly leads to error lvalue required as decrement operand. That’s because the direct decrement is illegal, so, it’s an assignment error.

#include <stdio.h>
int main() {
// This is illegal, don’t try this
int x, y;
x = -4–4;
y = -4–(-4);
printf(“x=%d y=%d”, x, y);
}

– Using a Pointer to a Variable Value

An attempt to use a pointer on a variable value will lead to lvalue required error. That’s because the purpose of the pointer sign (&) is to refer to the address of a variable, not the value of the variable.

In the code below, we’ve used the pointer sign (&) on the value of the Z variable. As a result, when you compile the code you get the error lvalue required as unary ‘&’ operand.

#include <stdio.h>
int main() {
int *p;
int z = 5;
p = &5; // Here is the error
return 0;
}

– Wrong Placement of Expression

If you place an expression in the wrong place, it’ll lead to an error lvalue required as operand. It gets confusing if you assign the expression to a variable used in the expression. Therefore, this can result in you assigning the variable to itself.

The following C++ code example will result in an error. That is because we’ve incremented the variable and we assign it to itself.

#include <iostream>
using namespace std;
int main() {
int y[3] = {3,4,5};
int *z=y;
z + 1 = z; // Error
cout << z;
return 0;
}

You can fix the lvalue required error by using equality operator during comparisons, using a counter variable as the value of the multiplication assignment operator, or using the ternary operator the right way. Not pre-incrementing a temporary variable, using pointer on a variable, not its value, and placing an expression on the right side will also help you fix this error.

Now that you know what is causing this error to appear, it’s now time to take actionable steps to fix the problem. In this section, we’ll be discussing these solutions in more detail.

– Use Equality Operator During Comparisons

During comparisons, use the equality operator after the left operand. By doing this, you’ve made it clear to the compiler that you are doing comparisons, so this will prevent an error.

The following code is the correct version of the first example in the code. We’ve added a comment to the corrected code so you can observe the difference.

#include <stdio.h>
int main() {
int a = 26;
int b = 13;
if (a % b == 0) { // Here is the correction
printf(“%s”, “It’s all good”);
}
}

– Use a Counter Variable as the Value of the Multiplication Assignment Operator

When doing computation with the multiplication assignment operator (*=), use the counter variable. Do not use another variable that can lead to an error. For example, in the code below, we’ve made changes to the second example in this article. This shows you how to prevent the error.

#include <stdio.h>
int findFactorial(int n) {
int result = 1, i;
for ( i = 1; i <=n; i++) {
result *= i; // Here is the correct part
}
return result;
}
int main() {
int n = 5;
int factorial = findFactorial(n);
printf(“%d”, factorial);
return 0;
}

– Use the Ternary Operator the Right Way

Use the ternary operator without assuming what should happen. Be explicit and use the values that will allow the ternary operator to evaluate. We present an example below.

#include <stdio.h>
int main() {
int x = 23, y;
y = x >= 23? 4: 12; // The correct ternary operation
printf(“%d”, y);
return 0;
}

– Don’t Pre-increment a Temporary Variable

That’s right, do not pre-increment a temporary variable. That’s because they only serve a temporary purpose.

At one point in this article, we showed you a code example where we use a pre-increment on a temporary variable. However, in the code below, we rewrote the code to prevent the error.

#include <stdio.h>
int main() {
int i = 5;
printf(“%dn”, (–i) * -1); // This should work as expected
}

– Use Pointer on a Variable, Not Its Value

The job of a pointer is to point to a variable location in memory, so you can make an assumption that using the variable value should work. However, it won’t work, as we’ve shown you earlier in the guide.

In the code below, we’ve placed the pointer sign (&) between the left operand and the right operand.

#include <stdio.h>
int main() {
int *p;
int z = 5;
p = &z; // This is right
printf(“%d”, p);
return 0;
}

– Place an Expression on the Right Side

When you place an expression in place of the left operand, you’ll receive an error, so it’s best to place the expression on the right side. Meanwhile, on the right, you can place the variable that gets the result of the expression.

In the following code, we have an example from earlier in the article. However, we’ve moved the expression to the right where it occupied the left operand position before.

#include <iostream>
using namespace std;
int main() {
int y[3] = {3,4,5};
int *z=y;
z = z + 1; // The correct form of assignment
cout << z;
return 0;
}

Lvalue Required: Common Questions Answered

In this section, we’ll answer questions related to the lvalue error and we’ll aim to clear further doubts you have about this error.

– What Is Meant by Left Operand of Assignment?

The left operand meaning is as follows: a modifiable value that is on the left side of an expression.

– What Is Lvalues and Rvalues?

An lvalue is a variable or an object that you can use after an expression, while an rvalue is a temporary value. As a result, once the expression is done with it, it does not persist afterward.

– What Is Lvalue in Arduino?

Lvalue in Arduino is the same as value in C, because you can use the C programming language in Arduino. However, misuse or an error could produce an error that reads error: lvalue required as left operand of assignment #define high 0x1.

What’s more, Communication Access Programming Language (CAPL) will not allow the wrong use of an lvalue. As a result, any misuse will lead to the left value required capl error. As a final note, when doing network programming in C, be wary of casting a left operand as this could lead to lvalue required as left operand of assignment struct error.

Conclusion

This article explained the different situations that will cause an lvalue error, and we also learned about the steps we can take to fix it. We covered a lot, and the following are the main points you should hold on to:

  • A misuse of the assignment operator will lead to a lvalue error, and using the equality operator after the left operand will fix this issue.
  • Using a pointer on the variable instead of the value will prevent the lvalue assignment error.
  • A pre-increment on a temporary variable will cause the lvalue error. Do not pre-increment on a temporary variable to fix this error.
  • An lvalue is a variable while an rvalue is a temporary variable.
  • Place an expression in the right position to prevent an lvalue error, as the wrong placement of expressions can also cause this error to appear.

Error lvalue required as left operand of assignmentYou don’t need to worry when you encounter this lvalue error as you are now well-prepared to handle the problem. Do share our guide when this topic arises in your tech conversations!

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Table of Contents

  • Scenario 1
  • Scenario 2
  • Scenario 3

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.

#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: 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:

#include <stdio.h>

int main()

{

    int number = 10 ;

    number + 1 = 20;

    return 0;

}

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:

#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: 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++.

Понравилась статья? Поделить с друзьями:
  • Ошибка f04 на газовом котле protherm как исправить
  • Ошибка error number 1062
  • Ошибка error null
  • Ошибка mac на терминале ingenico что делать
  • Ошибка error loading python dll