Expression must be a modifiable lvalue

Total
0
Shares

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?


Solution

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))

Source: StackOverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *