Saturday, 18 March 2017

error : lvalue required!!!!

One of the frequently facing error in programming is "lvalue required" so,lets discuss about some of the important points to handle those errors.

What is l-value


Every expression has l-value and r-value.l-value represents the memory location where an identifier or value is stored. r-value may be an expression or just a value that is stored in the memory.

Example :


consider the expression
var=5
 var   ->  l-value.
 =     ->  assignment operator.
 5     ->  r-value.
l-value refers to the memory location ,thus they must me variables.
There are many instances,where we get errors due to l-values of the expression.

Example 1:


l-value of an expression cannot be constant value.
int main()
{
  int var;
  2=var; //error.
  return 0;
}

Output:
prog.c:7:4: error: lvalue required 
   2=var;

Example 2:


l-value for an expression cannot be constant variable.
 int main()
{
  const var=5;
  var=10; //error.
  return 0;
}
Output :
prog.c:7:6: error: assignment of read-only
 variable 'var'
   var=10; 

Example 3:


l-value cannot be macro,this is because the macros gets expanded before processing the source code by the compiler. so all the macros get replaced by defined values before compiling.
 #define VAR 20
 int main()
 {
  VAR=10; //error.
   return();
 }
Output:
prog.c:5:6: error: lvalue required 
   VAR=10; 

Example 4:


l-value cannot be enum constant the reason is similar as that of macro substitution.Here also enum constants are substituted before compilation.
 enum{sun,mon,tue,wed}
 int main()
 {
  wed=10; //error
  return();
 }
Output :
prog.c: In function 'main':
prog.c:6:5: error: lvalue required 
wed=10;

Example 5:


l-value cannot be expression.
 int main()
 {
  int m=1,n;
 n+1=m; //error.
 return 0;
 }
Output:
rog.c: In function 'main':
prog.c:7:5: error: lvalue required 
 n+1=m;

Tips to Fix :


  • Never try to assign a value to constant value instead assign the value to a "variable".
  • l-value required error may occur even when we write comparison operator as "= =" instead of "==".so be cautious while dealing with the comparison operator.

No comments:

Post a Comment