Error lvalue required as decrement operand

I tried this on my gcc: int a=1; cout<<(--a)--; and the output is 0; but change it to cout<<--(a--); results in an error (lvalue required as decrement operand). Could someone enligh...

I tried this on my gcc:

int a=1;
cout<<(--a)--;

and the output is 0; but change it to

cout<<--(a--);

results in an error (lvalue required as decrement operand). Could someone enlighten me about this?

Thanks!

asked May 20, 2011 at 3:11

zw324's user avatar

zw324zw324

26.5k16 gold badges84 silver badges116 bronze badges

6

Both versions of ++ require lvalues as arguments, but the prefix version returns an lvalue as an argument, while the postfix version returns an rvalue.

Either way, you can’t modify the same object twice between sequence points, so your «working» example invokes undefind behavior. The output can be whatever the compiler feels like doing. If you’re just asking out of curiosity that’s fine, but if this is relevant to your actual code you might be doing something wrong.

answered May 20, 2011 at 3:16

Chris Lutz's user avatar

Chris LutzChris Lutz

72.2k16 gold badges128 silver badges182 bronze badges

4

predecrement --a decrements a, and then gives you back a itself. So you can then go on to modify it any way you want, including a postdecrement.

postdecrement a-- decrements a but gives you back a’s value before the decrement. It’s essentially giving you a copy of a. But you cannot then predecrement this copy. It’s not an lvalue, so there’s nothing to decrement. That’s why it’s an error.

Think of predecrement as returning a reference to a, and postdecrement as returning by constant value.

answered May 20, 2011 at 3:16

Tim's user avatar

TimTim

8,8023 gold badges38 silver badges56 bronze badges

3

(--a)--

This is undefined behavior, as you modify the same object twice without an intervening sequence point. The compiler is not required to report when you invoke UB – it can’t even detect UB in many situations. But if you turn on the right warnings (and you should look at what yours provides), it may be able to, sometimes.

--(a--)

Prefix decrement requires an lvalue, but postfix decrement returns an rvalue. This is an error that, unlike undefined behavior, the compiler is required to report.

answered May 20, 2011 at 3:19

Fred Nurk's user avatar

Fred NurkFred Nurk

13.7k4 gold badges37 silver badges62 bronze badges

The 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.

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.

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.

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:

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
int findFactorial(int n) <
int result = 1, i;
for ( i = 1; i – 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:

Many compilers will parse this as the following:

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
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
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
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
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
using namespace std;
int main() <
int y[3] = <3,4,5>;
int *z=y;
z + 1 = z; // Error
cout How To Fix Lvalue Required as Left Operand of Assignment
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
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
int findFactorial(int n) <
int result = 1, i;
for ( i = 1; i – 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
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
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
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
using namespace std;
int main() <
int y[3] = <3,4,5>;
int *z=y;
z = z + 1; // The correct form of assignment
cout 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.

You 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!

Источник

Solve error: lvalue required as left operand of assignment

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 a 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.

Solve error: lvalue required as left operand of assignment

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

Example 1:

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

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

Example 2:

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.

Example 3:

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.

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.

Источник

Adblock
detector

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

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

Цитата
Сообщение от Kastaneda
Посмотреть сообщение

попробуйте так

2) это undefined behavior, почитайте. (там правда в контексте языка С++, но думаю по данному вопросу особой разницы нет)

Ваш пример работает, но не могли бы вы более докладно объяснить в чем причина

прочитал я про undefined behavior в моем примере

и так точка следования у нас одна «;» объект expr изменяется только раз ++expr объект ch тоже раз при присваивании то есть изменение объектов expr и ch выполняется только по разу до точки следования, и тут начинается самое интересное… код

вызывает ту же ошибку! ну почему? ведь казалось бы порядок вычисления строго задан с помощью скобок и нет перекрытия точки следования?

Добавлено через 46 минут

Цитата
Сообщение от Kastaneda
Посмотреть сообщение

2) это undefined behavior, почитайте. (там правда в контексте языка С++, но думаю по данному вопросу особой разницы нет)

Все разобрался это не undefined behavior, хвала книге K&R expr в моем случае это имя массива указателей на чар, который нельзя инкрементировать(изменять) и который в частном случае может быть указателем на массив указателей. но его же изменять нельзя что я пытался сделать

Данная проблема решается объявлением указателя на указатель:

C
1
2
3
4
5
6
 char *expr[] = {"my", "w9rd", "the"};
      char **p_char;
 
      p_char = expr;
      ch = (*++p_char)[2];
      std::cout << ch;

все впорядке выводится символ ‘r’

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.

Начнём-с с C:

main(){
int i = 0;
--i++;
}

при попытке собрать:

$ gcc main.c -o main
main.c: In function 'main':
main.c:3: error: lvalue required as decrement operand

Внимательно читаем о Lvalue:

In C, the term L-value originally meant something that could be assigned to (coming from left-value, indicating it was on the left side of the = operator)

Т.о. декремент должен быть применён к lvalue, но для Си i++ не есть lvalue.
Схожая ситуация и с Java, javascript.

C++ так же ругается на ошибку, но если расставить скобки, то код работает.

#include <iostream>
int main(){
int i = 0;
std::cout << "(--i)++: " << (--i)++ << ", i: " << i << std::endl;
}

$ g++ main.cpp -o main && ./main 
(--i)++: -1, i: 0

В C++ действует т.н. временная переменная, которой и происходит присваивание временного же значения, которая в итоге будет присвоена обратно i.

А вот, что google выдаёт по запросу «(—i)++» lang:c++:

 805:   {
intelhex::lst_dblock::const_iterator prev = (--i)++; //Get an iterator to the previous element w/o changing i
//Check for gaps between blocks and fill them with NOP's

Логично, предположить, что схожим образом будут действовать и итераторы, для которых определены операции инкремента и декремента:

#include <iostream>
#include <vector>

int main(){
std::vector<int> v;
v.push_back( 5 );
v.push_back( 7 );
v.push_back( 9 );

for(std::vector<int>::iterator it = v.begin(); it != v.end(); ++it){
if (it != v.begin())
std::cout << "prev:" << *(--it)++ << std::endl;
std::cout << *it << std::endl;
}
}

Результат:

5
prev:5
7
prev:7
9

ps. Вот такой вот он «красивый» этот C++ — и как только ещё смеют говорить C++шники, что тернарный оператор сложно читать…

Improve Article

Save Article

  • Read
  • Discuss(30+)
  • Improve Article

    Save Article

    What will be the output of the following program?

    #include<stdio.h>

    int main()

    {

       int i = 10;

       printf("%d", ++(-i));

       return 0;

    }

    A) 11 B) 10 C) -9 D) None

    Answer: D, None – Compilation Error.

    Explanation:

    In C/C++ the pre-increment (decrement) and the post-increment (decrement) operators require an L-value expression as operand. Providing an R-value or a const qualified variable results in compilation error.

    In the above program, the expression -i results in R-value which is operand of pre-increment operator. The pre-increment operator requires an L-value as operand, hence the compiler throws an error.

    The increment/decrement operators needs to update the operand after the sequence point, so they need an L-value. The unary operators such as -, +, won’t need L-value as operand. The expression -(++i) is valid.

    In C++ the rules are little complicated because of references. We can apply these pre/post increment (decrement) operators on references variables that are not qualified by const. References can also be returned from functions.

    Puzzle phrased by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

    Ошибка компиляции кода Arduino: «lvalue требуется как левый операнд присваивания»

    Я получаю эту ошибку, когда пытаюсь скомпилировать свой код:

    lvalue требуется как левый операнд присваивания.

    Код считывается кнопками через аналоговый порт. Вот где ошибка (в void (loop)):

    while (count < 5){
        buttonPushed(analogPin) = tmp;
    
            for (j = 0; j < 5; j++) {
                    while (tmp == 0) { tmp = buttonPushed(analogPin); }                 //something wrong with the first half of this line!
    
            if(sequence[j] == tmp){
                            count ++;
                    }
    
            else { 
                lcd.setCursor(0, 1); lcd.print("Wrong! Next round:");                       delay(1000);
                            goto breakLoops;
                    }
    
            }
    }
    
    breakLoops:
    elapsedTime = millis() - startTime;
    

    На самом верху у меня: int tmp;

    3 ответы

    buttonPushed(analogPin) = tmp;
    

    Эта линия не работает. buttonPushed является функцией и может читать только из analogPin; вы не можете присвоить результат функции в C. Я не уверен, что вы пытаетесь сделать, но я думаю, что вы, вероятно, хотели вместо этого использовать другую переменную.

    ответ дан 25 мар ’12, в 15:03

    У вас есть такая строка:

         buttonPushed(analogPin) = tmp;
    

    Вместо этого вы можете захотеть:

         tmp = buttonPushed(analogPin);
    

    С оператором присваивания объект слева от = оператор получает значение справа от = оператор, а не наоборот.

    ответ дан 25 мар ’12, в 15:03

    Проблема здесь в том, что вы пытаетесь назначить временное значение / rvalue. Для присвоения в C требуется lvalue. Я предполагаю подпись твоей buttonPushed функция по существу следующая

    int buttonPushed(int pin);
    

    Здесь buttonPushed функция возвращает копию найденной кнопки, которую не имеет смысла назначать. Чтобы вернуть фактическую кнопку вместо копии, вам нужно использовать указатель.

    int* buttonPushed(int pin);
    

    Теперь вы можете сделать свой код назначения следующим

    int* pTemp = buttonPushed(analogPin);
    *pTemp = tmp;
    

    Здесь присвоение находится в месте, которое является lvalue и будет законным.

    ответ дан 25 мар ’12, в 16:03

    Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

    c
    loops
    while-loop
    arduino

    or задайте свой вопрос.

    Понравилась статья? Поделить с друзьями:
  • Error lua gui forms playerseditorform helpers lua 300 attempt to index a nil value field
  • Error lp011 section placement failed iar
  • Error low level components
  • Error looser throw specifier for virtual
  • Error lookup скачать торрент