lvalue and rvalue c++11
In C language, lvalue and rvalue were very simple, like if any thing is present on left hand side (LHS) of assignment operator is lvalue and if present on right hand side (RHS) of assignment operator is rvalue but in C++11, it has become little complex.
lvalue:
If any expression gives you an object then its lvalue and object must have below qualities :
- It has identity (it has some name).
- It has memory address (We can take address of it).
- It will persist after expression.
- Example: int a = 10; (a is lvalue)
rvalue:
If any expression gives you a value then its rvalue(In other word, it is temporary object) and It must have below qualities :
- It does not have any name (They are temporary objects)
- It does not memory address (We cannot take address of it).
- It will NOT persist after expression (live temporarily during evaluation of expression and destroyed at next semicolon).
- Example: int a = 2 + 3 ; (during evaluation of expression( temp object = 2+3), temporary object will be created then it will be assigned to ‘a’ variable and after that it will be destroyed)
Note: Every expression is either lvalue or rvalue but not both.
Difference between lvalue and rvalue (lvalue vs rvalue):
Characteristics | lvalue | rvalue |
It has Name | Yes | No |
It has Memory Address | Yes | No |
It is Temporary object | No | Yes |
It is eligible for move operation | No | Yes |
It will be destroyed after evaluation of expression | No | Yes |
Source code with example:
/* Program: lvalue and rvalue Author: Alpha Master Date: 3 March 2021 */ //Header File #include<iostream> int main() { std::cout<<"lvaue & rvalue"<<std::endl; int a = 5; std::cout<<"a:"<<a<<" a address:"<<&a<<std::endl; int b = 1+2; //when trying to get address of literals //std::cout<<" temp address:"<<&(1+2)<<std::endl; //error: lvalue required as unary ‘&’ operand return 0; }
Output:
lvaue & rvalue a:5 a address:0x7ffdd7f688e0