Friday, March 4, 2016

What is the Lvalue required error in C/C++ ?


Dear Folks,

It is a common error encountered while learning C/C++ programming.C/C++ compilers flag this error whenever the program tries to modify the constant values.

Constant in programming context can be defined as a value, that does not change during program execution. In programming, constants are literal values and can be classified as below,



In programming, normally, when we define a mathematical expression, it has two components around assignment operator, one is the Lvaue and the other is Rvalue as shown in the image...
It is clear from the above expression that, the Lvaue is Left side component and Rvalue is the result of evaluation of right side component of an assignment(=).

Thus it can be concluded that, variables used in programming can be used as Lvalues as well as Rvalues, where as constants are always Rvalues they can not be used as Lvalues. If we try to use a constant as an Rvalue, the compiler demands you to provide a Lvalue, as a constant can not be modified.

for instance
int a,b;
a=5;  ----(1)// here 'a' is Lvalue and 5 is Rvalue
b=a;  ----(2)// here 'b 'is Lvalue and 'a' is Rvalue
Here we can notice that in equation(1) 'a' is used as Lvaule, and the same , is been used in equation(2) as Rvalue, So we say a variable can become Lvalue or Rvalue...

Let's say
#define SIZE 10 // this is how we define constants in C language, now SIZE is a constant
main()
{
  printf("%d\n", SIZE++);
}
This program is compiled with an error " Lvalue required", as we are trying to modify a constant.
SIZE++ is actually SIZE=SIZE+1 , here the constant is used as Rvalue, hence compiler raises an objection, that a constant can not be modified.

Similarly there is another scenario where we get this error very commonly, can you Guess ?

YES, you are right ! It is when you try to modify base address of an array by it's NAME. In programming, the base address of an array by array-name is constant. It can be copied in some  other variable and then can be modified.

 A sample program to  demonstrates this concept.
Program 1: Demo Lvalue required Error
Program 2: Demo Lvalue required Error
We can notice here, program:1 is compiled with an error Lvalue required, for the statement *(++x), as the program is modifying the base address by an array-name(x), where as program:2 is successfully compiled with no errors, and we get an output. In program:2, though, we are modifying the base address , the program is compiled with no errors, as it is done with another variable, not using an array-name.

Did you find this post useful ? Please reply through blog itself...
If any suggestions and comments, you are most welcome....



No comments:

Post a Comment