Меню

Expression must be a modifiable lvalue ошибка

I have this following code:

int M = 3; 
int C = 5; 
int match = 3;
for ( int k =0; k < C; k ++ )
{
    match --; 
    if ( match == 0 && k = M )
    {
         std::cout << " equals" << std::endl;
    }
}

But it gives out an error saying:

Error: expression must be a modifiable value

on that «if» line. I am not trying to modify «match» or «k» value here, but why this error? if I only write it like:

if ( match == 0 )

it is ok. Could someone explain it to me?

Brian Tompsett - 汤莱恩's user avatar

asked Oct 5, 2012 at 11:45

E_learner's user avatar

2

The assignment operator has lower precedence than &&, so your condition is equivalent to:

if ((match == 0 && k) = m)

But the left-hand side of this is an rvalue, namely the boolean resulting from the evaluation of the sub­expression match == 0 && k, so you cannot assign to it.

By contrast, comparison has higher precedence, so match == 0 && k == m is equivalent to:

if ((match == 0) && (k == m))

answered Oct 5, 2012 at 11:49

Kerrek SB's user avatar

Kerrek SBKerrek SB

457k91 gold badges866 silver badges1073 bronze badges

3

In C, you will also experience the same error if you declare a:

char array[size];

and than try to assign a value without specifying an index position:

array = ''; 

By doing:

array[index] = '0';

You’re specifying the accessible/modifiable address previously declared.

answered Apr 17, 2015 at 14:20

Alan's user avatar

AlanAlan

1,4093 gold badges22 silver badges36 bronze badges

0

You test k = M instead of k == M.
Maybe it is what you want to do, in this case, write if (match == 0 && (k = M))

answered Oct 5, 2012 at 11:48

tomahh's user avatar

tomahhtomahh

13.2k3 gold badges49 silver badges70 bronze badges

0

Remember that a single = is always an assignment in C or C++.

Your test should be if ( match == 0 && k == M )you made a typo on the k == M test.

If you really mean k=M (i.e. a side-effecting assignment inside a test) you should for readability reasons code if (match == 0 && (k=m) != 0) but most coding rules advise not writing that.

BTW, your mistake suggests to ask for all warnings (e.g. -Wall option to g++), and to upgrade to recent compilers. The next GCC 4.8 will give you:

 % g++-trunk -Wall -c ederman.cc
 ederman.cc: In function ‘void foo()’:
 ederman.cc:9:30: error: lvalue required as left operand of assignment
          if ( match == 0 && k = M )
                               ^

and Clang 3.1 also tells you ederman.cc:9:30: error: expression is not assignable

So use recent versions of free compilers and enable all the warnings when using them.

answered Oct 5, 2012 at 11:48

Basile Starynkevitch's user avatar

What causes expression must be a modifiable lvalueAs you use conditional statements in c++ you may come across expression must be a modifiable lvalue error. You are likely to see this error message in most conditional expressions when using the assignment operator (=) instead of the comparison operator (==). In this post, you will learn the cause of this error and how you can solve it.

Contents

  • What Causes Expression Must Be a Modifiable Lvalue
    • – Example One: Triggering Expression Must Be a Modifiable Lvalue in C++
    • – Example Two
    • – Example Three
  • How To Solve This Error
    • – The Solution to Example One
    • – The Solution to Example Two
    • – The Solution to Example Three
  • FAQ Section
    • – What Is the Meaning of Expression Must Be a Modifiable value?
    • – What Does Lvalue Mean?
    • – What Triggers Lvalue Required Error?
    • – What Is an Rvalue and Lvalue in C++?
    • – In C++, What Is a Universal Reference
    • – What Is the Meaning of Lvalue Required as Increment Operand?
    • – Which Operator Can You Use To Find the Lvalue of a Variable?
    • – What Is an Expression in C++
    • – When Should an Expression in C++ Be Modifiable?
  • Conclusion

You will get this error message as a result of an expression not producing an lvalue (value on the left side of an assignment). The “l” in the “lvalue” stands for something on the left side of the (=) operator. It means you are attempting to give the value on the right a place in the memory whose name is on the left.

Therefore, whatever is on the left should denote something that has an allocation in memory and lets you modify it. However, if you accidentally try to assign something that is not a left operand an assignment operator (=) instead of a comparison operator (==), you will get this error.

– Example One: Triggering Expression Must Be a Modifiable Lvalue in C++

Suppose you are trying to compare if the sum of two numbers is equal to the third number in C++. One way you can accomplish this is through conditional statements. Here is an example of how you can trigger this error using an assignment operator instead of a comparison operator.

#include <iostream>
using namespace std;
int main()
{
int X = 2;
int Y = 1;
int Z = 3;
// This is the same as if ( X + Y = Z )
if ( (X + Y) = Z) // Error arising from assignment operator (=)
{
std::cout << ” Comparison match” << std::endl;
}
return 0;
}

In this example, you are assigning Z variable an expression (X+Y). Thus, the compiler is going to throw the lvalue error. Every binary + operator results in rvlaue. So, the expression X + Y =Z is an error. Usually, the binary operator (+) takes high precedence over the assignment operator (=). As such X+Y is an rvalue.

Sometimes an operator may use an lvalue operand but result in rvalue. A good example of such an operator is the unary & operator.

– Example Two

Suppose you now want to do a comparison of values by combining the comparison operator and &&. Here is an example of how you can trigger this error by using the assignment operator instead of the comparison operator.

#include <iostream>
using namespace std;
int main()
{
int X = 2;
int Y = 3;
int Z = 3;
if (X == 2 && Y = Z) // Error arising from assignment operator (=)
{
std::cout << “Comparison is a match” << std::endl;
}
return 0;
}

– Example Three

Suppose you have variable A that you wish to print if the value is equal to a certain value. If in the condition statement you end up providing the value of A as the lvalue instead of A, the c++ compiler will throw this error.

#include <iostream>
using namespace std;
int main()
{
int A = 20;
if (20 = A) // *** If you run this program, this line will throw the error.
{
printf(“The value of A is 20.n”);
}
}

The condition statement uses an expression that tries to assign A to the literal value 20. It will generate the error because 20 is not a valid lvalue.

How To Solve This Error

Since the root cause of the error is the wrong use of the assignment operator when creating conditional statements, the solution is quite easy. You only need to take a quick look at the conditional statement to establish the source of the error.

– The Solution to Example One

Say you want to solve the error you got from the first example where you were comparing the sum of two numbers to a third number. You can easily get rid of this error as follows:

#include <iostream>
using namespace std;
int main()
{
int X = 2;
int Y = 1;
int Z = 3;
// This is the same as if ( X + Y == Z )
if ( (X + Y) == Z) // Solution requires replacing assignment operator (=) with a comparison operator (==)
{
std::cout << ” Comparison is a match” << std::endl;
}
return 0;
}

To resolve this error you need to ensure you do not assign Z variable to an expression X + Y like so (X + Y = Z). Instead, use the comparison operator (==). This simple modification of the code will solve this conditional statement error.

Another thing you should keep in mind is that you need to use brackets to make it easy to understand the code. Also, brackets help you get rid of precedence errors.

– The Solution to Example Two

In example two, you were comparing three numbers a pair at a time. In this example, you introduced the && which has higher precedence than the assignment operator. To solve the error in this example, you need to use the comparison operator instead of the assignment operator. So, the condition should be (X == 2 && Y == Z) to eradicate this error.

#include <iostream>
using namespace std;
int main()
{
int X = 2;
int Y = 3;
int Z = 3;
// The same as if ((X == 2) && (Y == Z))
if (X == 2 && Y == Z) // Solved the error arising from assignment operator (=)
{
std::cout << “Comparison is a match” << std::endl;
}
return 0;
}

– The Solution to Example Three

If you recall, in example three, you mistakenly used the value of A as an lvalue in your conditional expression resulting in this error. To get rid of the error, ensure you properly use operands in the condition statement. Here is how you can solve this error:

#include <iostream>
using namespace std;
int main()
{
int A = 20;
if (A = 20) // *** The erroneus (20 = A) has been solved. If you run this program, this line will not throw the error.
{
printf(“The value of A is 20.n”);
}
}

FAQ Section

– What Is the Meaning of Expression Must Be a Modifiable value?

The error indicates that the lvalue (the value on the left-hand side) in a conditional statement is not modifiable. It means you are attempting to assign something to an operand that does not belong to the left side of the assignment operator (=).

– What Does Lvalue Mean?

In c++, an lvalue is a value permitted to be on the left-hand side of the assignment operator (=). The lvalue allows examination or alteration of the designated object. However, there are object types you cannot modify such as arrays, const-qualified, and incomplete types. As such, these values cannot appear on the left side of the assignment operator.

For instance, the variable A can be lvalue that you can modify to be 20 using the assignment operator. However, note that you cannot use 20 as the lvalue for A. Usually, the lvalue is addressable and assignable.

– What Triggers Lvalue Required Error?

The error arises when you put constants as lvalue and variables on the right-hand side of the assignment operator. It means you are unable to assign a value to constants or anything without a memory address. In essence, to assign a value you need a variable.

– What Is an Rvalue and Lvalue in C++?

In c++ expressions, both rvalues and lvalues are important. In simple terms, the lvalue acts as an object reference while the rvalue is the value. The differences between rvalues and lvalues appear when you start writing expressions.

– In C++, What Is a Universal Reference

The && in type declarations showcase either a universal reference or rvalue reference. A universal value in c++ can either be an lvalue or rvalue reference.

– What Is the Meaning of Lvalue Required as Increment Operand?

Usually, any pre-increment operator demands an lvalue as an operand. If it is not present, the compiler will throw this error. Both decrement and increment operators must update the operand at every sequence point hence the need for an lvalue. Unary operators like + and – do not need an lvalue as an operand. Thus, -(++i) expression is valid.

– Which Operator Can You Use To Find the Lvalue of a Variable?

The assignment operator (=) holds the value of a variable. In other words, it assigns a variable its value.

– What Is an Expression in C++

In c++, an expression denotes a statement that contains both a data type and a value. For instance, a declaration statement defines a variable. You can think of it as a holding tank for a value such as a character or a number.

– When Should an Expression in C++ Be Modifiable?

In all conditional expressions especially when using the assignment operator (=) instead of the comparison operator (==).

Conclusion

If you get the lvalue error from a c++ compiler, you should look out for the following tell-tale signs:

  • Check the conditional statements in your program
  • Establish if you are using the assignment operator (=) instead of a comparison operator (==)
  • Check if you are correctly applying the operator precedence in your expression
  • Use brackets in expressions and comparisons to avoid mistakes

Expression must be a modifiable lvalue errorsThat’s it! Whenever a c++ compiler throws the lvalue error, you can now easily pinpoint and solve it.

  • 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

Normally these type of c++ error occurs in conditional statments. For any conditional expression if we are using assignment operator(=) in-stand of comparison (==) then mostly c++ expression must be a modifiable lvalue error occurs.

#include <iostream>
using namespace std;

int main()
{
    int A = 0; 
    int B = 1;
    int C = 1;

    // It is same as if ( (A + B) = C )
    if ( A + B = C ) // ERROR
    {
         std::cout << " Comparison match" << std::endl;
    }
        return 0;
}

Output:

error: lvalue required as left operand of assignment c++ expression must be a modifiable lvalue
error: lvalue required as left operand of assignment

Here we are assigning C variable to expression (A+B) so compiler is giving error of lvalue required as left operand of assignment. if we want to resolve this error then we have to use comparison (==) operator. Also always make sure to add brackets “(” and “)” for easy understanding and also to avoid any operator precedence errors.

SOLUTION :

    if ( (A + B) == C ) // SOLUTION using (==)
    {
         std::cout << " Comparison match" << std::endl;
    }

By modifying this code we can easily resolve lvalue required as left operand of assignment error from condition.

2) c++ expression must be a modifiable lvalue (Scenario-2)

#include <iostream>
using namespace std;

int main()
{
    int A = 0; 
    int B = 1;
    int C = 1;
    
    // Same as if ( (A == 0 && B) = C )
    if ( A == 0 && B = C ) // ERROR
    {
         std::cout << " Comparision match" << std::endl;
    }
        return 0;
}

Output:

c++ expression must be a modifiable lvalue
error: lvalue required as left operand of assignment

SOLUTION :

    if ( (A == 0) && (B == C) ) // SOLUTION using (==)
    {
         std::cout << " Comparision match" << std::endl;
    }

Here assignment(=) operator has lower precedence then &&. So if we change assignment operator to comparison (==) operator then it has higher precedence so (A==0) && (B==C) condition will work proper and expression must be a modifiable lvalue error will be resolved.

CONCLUSION:

Whenever your c++ compiler get error for expression must be a modifiable lvalue, you always need to check below points

  1. Check Assignment (=) operator is used in stand of comparison operator (==)
  2. Check Operator precedence for expression is correctly applied
  3. Try to use bracket for each expression and comparisons for avoiding mistakes

SEE MORE:

Reader Interactions

  • Forum
  • General C++ Programming
  • Expression must be a modifiable lvalue

Expression must be a modifiable lvalue

For some reason I can’t get my addNewPurchase function to work. No matter which way I spin it, it will usually give me an error message stating that I need to have a modifiable lvalue, and if it does not give me that error then it makes the numbers extremely large. Just looking for a hint as to what I am doing wrong.

I want it to be able to add a new variable to the old one and then have the sum take the place when I display it. So if someone bought 2 books and then 3, I want the next display to say they bought 5 in total.

Member.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <string>
#include <iostream>
#include "member.h"

// Write code for the following member functions:
/*Constructor. The constructor should accept the person’s name and member identification number. 
						These values should be assigned to the object’s memberName and memberID data members. 
						The constructor should also assign 0 to numBooks and purchaseAmt.*/

memberType::memberType(string name, string id) {

	memberName = name;
	memberID = id;
	int numBooks = 0;
	double purchaseAmt = 0;

}

/*Accessor.	Appropriate accessor functions to get the values stored in an object’s memberName, 
					memberID, numBooks, and purchaseAmt data members.*/

string memberType::getName() {

	return memberName;

}

string memberType::getId() {

	return memberID;

}

int memberType::getNumBooks() {


	return numBooks;
}

double memberType::getAmt() {


	return purchaseAmt;
}

/*addNewPurchase. The addNewPurchase function should accept the number of books for a new purchase and 
				the total amount of the purchase in dollars as arguments. 
				The function should add these argument values to the existing numBooks and purchaseAmt data member.

*/

void memberType::addNewPurchase(int numOfBooks, double amount) {

	numBooks + numOfBooks = numBooks;
	purchaseAmt + amount = purchaseAmt;

}

Member.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#ifndef MEMBER_H
#define MEMBER_H
#include <string>
#include <iostream>

using namespace std;

//define the class members and member function prototypes here

class memberType {

private:

	string memberName;
	string memberID;
	int numBooks;
	double purchaseAmt;

public:

	memberType(string name, string id);
	string getName();
	string getId();
	int getNumBooks();
	double getAmt();

	void addNewPurchase(int numOfBooks, double amount);

};

#endif 

Client.Cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <string>
#include <iomanip>
#include "member.h"

using namespace std;

int main() {

	string Name, ID;
	int Books;
	double Amt;

	cout << "Welcome! Thank you for choosing Enmanuel's Book Store.n";

	//Promput user for Name and ID

	cout << "Please enter your Member Name: n";
	cin >> Name;
	cout << endl;

	cout << "Please enter your Member ID: n";
	cin >> ID;
	cout << endl;

	//Creates the memberType object

	memberType obj(Name, ID);

	//Prompt user for Number of Books and Amount

	cout << "Please enter the amount of books you are purchasing: n";
	cin >> Books;
	cout << endl;

	cout << "Please enter the cost for all of your books: n";
	cin >> Amt;
	cout << endl;

	//Displays member info as well as purchase info

	cout << "Your Member Name is: " << obj.getName() << endl;
	cout << "Your Member ID is: " << obj.getId() << endl;
	cout << "The number of books you purchased is: " << obj.getNumBooks() << endl;
	cout << "The total cost of your purchase is:  " << obj.getAmt() << endl;

	cout << endl;

	//Second Purchase

	cout << "Please enter the amount of books you are purchasing: n";
	cin >> Books;
	cout << endl;

	cout << "Please enter the cost for all of your books: n";
	cin >> Amt;
	cout << endl;

	obj.addNewPurchase(Books, Amt);

	cout << "Your Member Name is: " << obj.getName() << endl;
	cout << "Your Member ID is: " << obj.getId() << endl;
	cout << "The number of books you purchased is: " << obj.getNumBooks() << endl;
	cout << "The total cost of your purchase is:  " << obj.getAmt() << endl;

	cout << endl;

	//Third Purchase

	cout << "Please enter the amount of books you are purchasing: n";
	cin >> Books;
	cout << endl;

	cout << "Please enter the cost for all of your books: n";
	cin >> Amt;
	cout << endl;

	obj.addNewPurchase(Books, Amt);

	cout << "Your Member Name is: " << obj.getName() << endl;
	cout << "Your Member ID is: " << obj.getId() << endl;
	cout << "The number of books you purchased is: " << obj.getNumBooks() << endl;
	cout << "The total cost of your purchase is:  " << obj.getAmt() << endl;

	system("pause");
	return 0;
}

Last edited on

1
2
	numBooks + numOfBooks = numBooks;
	purchaseAmt + amount = purchaseAmt;

You can’t assign things like this. The explanation depends on how technical you want to get, but basically when you add two ints together, you get a temporary value that can be used for further calculator or assignment, but it doesn’t make any sense to assign a value to a temporary value.

The = operator always assigns the right-hand side value to the left-hand side. It doesn’t work the other way around. i.e the information always flows to the left.

Even if legal, it would make something like this occur:

1
2
3
int temp = numBooks + numOfBooks;
temp = numBooks;
// numBooks, numOfBooks are still unchanged 

What you’re actually trying to do is increment numBooks and purchaseAmt, it looks like.

numBooks = numBooks + numOfBooks;
or, shorter:
numBooks += numOfBooks;

PS: I would urge you to have better names for your variables. What is the logical difference between numBooks and numOfBooks? Perhaps changed «numOfBooks» to «numBooksPurchased«.

Last edited on

You are trying to assign the new value to the existing variable. The syntax is:

<var> = <expression>

You were very close. Use these lines instead:

1
2
numBooks = numBooks + numOfBooks;
purchaseAmt = purchaseAmt + amount;

Topic archived. No new replies allowed.

Здравствуйте:
При компиляции возникает ошибка:
Error: C:CDAVRKRR.c(73): the expression must be a modifiable lvalue

Хотя буквально год назад компилировал вроде как этот же код, и все проходило гладко. А сейчас достал его, и не могу понять где ошибка.

#include <mega8.h>
#include <lcd.h>
#include <delay.h>
#include <stdio.h>
#include <stdlib.h>

#define ADC_VREF_TYPE 0x00
#define V 5

// Инициализация LCD
#asm
   .equ __lcd_port=0x18 ;PORTB
#endasm

//Функция для работы с АЦП
unsigned int read_adc(unsigned char adc_input)
{
ADMUX=adc_input | (ADC_VREF_TYPE & 0xff);
delay_us(10);
ADCSRA|=0x40;
while ((ADCSRA & 0x10)==0);
ADCSRA|=0x10;
return ADCW;
}

void main(void)
{
char acpread[5];
char acptry[5];
int j;

PORTB=0x00; //скорее всего нужно настроить на вывод
DDRB=0x00;

PORTC=0x00;
DDRC=0x00;

PORTD=0x00;
DDRD=0x00;

TCCR0=0x00;  //Регистр управления таймером
TCNT0=0x00;  //Счетный регистр
TCCR1A=0x00;
TCCR1B=0x00;
TCNT1H=0x00;
TCNT1L=0x00;
ICR1H=0x00;
ICR1L=0x00;
OCR1AH=0x00;  //Регистр сравнения
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;
ASSR=0x00;    //Регистр таймера в ассинхроном режиме
TCCR2=0x00;
TCNT2=0x00;
OCR2=0x00;
MCUCR=0x00;
TIMSK=0x00;   //Разрешение и запрет прерываний по таймеру
UCSRA=0x00;   //Регистры управления и состояни
UCSRB=0x18;   //Регистры управления и состояни
UCSRC=0x86;   //Регистры управления и состояни
UBRRH=0x00;   //Регистры ввода-вывода
UBRRL=0x4D;
ACSR=0x80;
SFIOR=0x00;
ADMUX=ADC_VREF_TYPE & 0xff;  //Регистр управления мультиплексером
ADCSRA=0x85;  //Регистр управления АЦП

lcd_init(16); // Инициализация ЖК
while (1)
      {
      itoa(read_adc(1), acpread);
      acptry = acpread*V/1024;
      j = 0;      //цикл для вывода значения с фотодатчика
      lcd_gotoxy(0,0);
      while(j<3){
      lcd_putchar(acptry[j]);
      delay_ms(200);
      j++;
      }
      }
};

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Expression expected ошибка vba
  • Expression cannot be used as a function ошибка