Monday, November 9, 2015

c++ : lvalue and rvalue



An object is a manipulatable region of storage; an lvalue is an expression referring to an object....The name 'lvalue' comes from the assignment expression E1 = E2 in which the left operand E1 must be an lvalue expression.
 C Programming Language (Prentice-Hall, 1988)



What is sometimes called 'rvalue' is in this standard described as the 'value of an expression'.

C++ definition

Every expression is either an lvalue or an rvalue.
C++ 2003 Standard 


lvalues and rvalues got their names from their roles in assignment expressions 
lvalues refers to objects and are addressable.

int a; // lvalue
char* p;
// *p is an lvalue. '*' operator returns an l-value
*p = 'c'; // OK, we can assign an l-value
*(p + 1) = 'd'; // OK

Conceptually, an rvalue is just a value; it doesn't refer to an object

int a = 5; // 5 is an rvalue
int b = 8; // 8 is an rvalue
State_te state = State_Idle; // State_Idle is an rvalue;

5 = b; // Error ! we can not assign an rvalue
State_Idle = 8; // Error ! we can not assign an rvalue
a = &5; // Error ! & Operator requires an lvalue and returns an rvalue
&b = 8; // Error ! & returns an rvalue 

Note: In C++, rvalues can refer to objects but are still not lvalues.


Post a Comment