Sunday, May 22, 2011

lvalue required as left operand of assignment


"lvalue required as left operand of assignment"
This is how the C / C++ compiler would complain if we try to assign a value to some constant.
We assign values to variables using assignment operator(=) in C / C++. The assignment operator assigns the value of the right hand side argument to the left hand side variable. for example, in the following statements:

     int a,b;
b=20;
a=b;

The line #2 will assign the value 20 to the variable b. The line #3 will assign the value of b (20) to the variable a. This works fine as the values are being assigned to variables not to the constants. What will happen if we change the above code as follow and try to compile?

int a,b;
b=5;
20=b;
a=b;

The compile will prompt the error "lvalue required as left operand of assignment" for line #3. This is because the value of b (5) is being assigned to a constant (20). The constants can not change their value, so the expression in line #3 is invalid.
Two values are associated with the assignment operator : the lvalue and the rvalue. Lvalue is an expression which is present at the left hand side of the assignment operator and rvlaue is present at the right hand side. The error “Lavalue required” means that the expression present in the left hand side of the assignment operator should not be there as the value can not be assigned to it.

Here is another code snippet that will show another scenario where the error occurs:

#include <stdlib.h>
void main()
{
int arr[10];
int* ptr;
ptr=(int*) calloc(2,10);
arr=ptr; //lvalue required error will be prompted for this
}

Here at line #7 the value is being assigned to a constant pointer, so the error will occur. The line #7 is trying to make the pointer arr point to the location allocated by calloc in line #6. This  is invalid because the array name(arr) is a constant pointer.

No comments:

Post a Comment