Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 520
E_learner Avatar asked Oct 05 '12 11:10

E_learner


People also ask

What does expression must be a modifiable lvalue mean?

– 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 is a modifiable lvalue?

For example, a const object is an lvalue that cannot be modified. The term modifiable lvalue is used to emphasize that the lvalue allows the designated object to be changed as well as examined. Lvalues of the following object types are not modifiable lvalues: An array type.


2 Answers

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)) 
like image 58
Kerrek SB Avatar answered Oct 01 '22 08:10

Kerrek SB


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 = '\0';  

By doing:

array[index] = '0\'; 

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

like image 37
Alan Avatar answered Oct 01 '22 08:10

Alan