Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How there is Lvalue required error

Tags:

c

lvalue

There is a piece of code which is producing error of "Lvalue required". The code is as,

     #include<stdio.h>
     #include<conio.h>
     #define max 10
     int main()
     {
      printf("%d",max++);
      return 0;
     }

It was evident that Lvalue error will come in above code so i changed the code to

     int a;
     printf("%d",a=max++); 

I thought now the value of constant is assigned to a proper variable but still the error appeared. Then i checked for

     printf("%d",a=max+1);

it works without any error.What is the problem with the second piece of code ?

like image 924
mrigendra Avatar asked Sep 09 '13 11:09

mrigendra


People also ask

How do you solve lvalue errors?

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.

Why does lvalue expected occur?

L-value error generally occur when we are using assignment operator. While using assignment operator the left hand operand must be a variable. For example let us take a variable x, and lets try to assign it a value 5.

How do you solve lvalue 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 ( rvalue s), so they are rvalue s. so the order doesn't matter and if you forget to use == you will get this error.

What is lvalue in C++ programming?

An lvalue is an expression that yields an object reference, such as a variable name, an array subscript reference, a dereferenced pointer, or a function call that returns a reference. An lvalue always has a defined region of storage, so you can take its address.


2 Answers

max is a literal so max++ will fail. (Just as 10++ will fail).

However, max + 1 is valid (just as 10 + 1 is).

Remember that #defines are resolved by the preprocessor which happens before compilation takes place.

To explain your compiler's return error:

Loosely speaking, an lValue is the thing on the left hand side of an assignment; i.e. in

a = b;

a is the lValue. The statement 10 = b; is clearly meaningless (you can't assign a value to 10): more formally it is invalid since 10 is not an lValue.

like image 115
Bathsheba Avatar answered Sep 28 '22 02:09

Bathsheba


max will be replaced by 10 after preprocessing, so

max++ => 10++      //Error  ++ requires lvalue
a=max++ => a=10++  //Error  same as above

a=max+1 => a=10+1 //Works
like image 20
P0W Avatar answered Sep 28 '22 02:09

P0W