lvalue & rvalue in C++

Let's see first what's the problem in this. 

#include <iostream>

int main()
{

   int x[3] = {4,5,6};
   int *p = x;
   p + 1 = p; /* compiler shows error saying 
                 lvalue required as left 
                 operand of assignment */
   std::cout << p;
   return 0;
}

Output:

1
2
3
main.cpp: In function ‘int main()’:
main.cpp:8:12: error: lvalue required as left operand of assignment
8 |    p + 1 = p; /* compiler shows error saying
  |    

Click here to debug the above code.

When you have an assignment operator in a statement, the LHS of the operator must be something the language calls an lvalue. If the LHS of the operator does not evaluate to an lvalue, the value from the RHS cannot be assigned to the LHS.


You cannot use:

10 = 20;    


since 10 does not evaluate to an lvalue.


You can use:


int i;                
i = 20;             


since i does evaluate to an lvalue.


You cannot use:


int i;               
i + 1 = 20;     

since i + 1 does not evaluate to an lvalue.


Put simply, an lvalue is something that can appear on the left-hand side of an assignment, typically a variable or array element.


So if we define int *p, then p is an lvalue. p+1, which is a valid expression, is not an lvalue.




What is lvalue?


  • An lvalue is an object reference.  The difference between lvalues and rvalues plays a role in the writing and understanding of expressions.
  • In C++ an lvalue is something that points to a specific memory location. 
  • lvalues live a longer life since they exist as variables. 
  • It's also fun to think of lvalues as containers.


Examples: 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.


What is rvalue?


  • A rvalue is a value. An rvalue is an expression that is not an lvalue. 
  • A rvalue is something that doesn't point anywhere.
  •  In general, rvalues are temporary and short lived. 
  •  rvalues as things contained in the containers. Without a container, they would expire.


Examples of rvalues include literals, the results of most operators, and function calls that return nonreferences. An rvalue does not necessarily have any storage associated with it.



Reference


Definition of lvalue & rvalue

Good link to know about reference

Comments