Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a pointer an lvalue or rvalue?

Tags:

c++

pointers

In other post, I came across

(5.2.9/8) An rvalue of type "pointer to member of D of type cv1 T" can be converted to an rvalue of type "pointer to member of B of type cv2 T", where B is a base class (clause 10) of D,

Note this from language standard. so my question,

int i = 0;
int *p = &i;
*p = 1;

Is pointer an lvalue in all the cases? When does it is treated as rvalue?

like image 340
user1086635 Avatar asked Dec 09 '11 19:12

user1086635


2 Answers

A pointer is not the kind of thing that can be an rvalue or an lvalue. A pointer is a type. The only thing that can be an rvalue or an lvalue is an expression.

Consider this similar question: "Is an integer an lvalue or an rvalue". Well, neither. "3" is an integer, and an rvalue. "3=i;" is illegal. But "i=3;" is legal if 'i' is an integer. So 'i' is an integer and an lvalue. '3' is an integer and a rvalue.

like image 118
David Schwartz Avatar answered Oct 13 '22 17:10

David Schwartz


According to c standard 2011:

Except when it is the operand of the sizeof operator, the _Alignof operator, the unary & operator, the ++ operator, the -- operator, or the left operand of the . operator or an assignment operator, an lvalue that does not have array type is converted to the value stored in the designated object (and is no longer an lvalue); this is called lvalue conversion.

...

The name ''lvalue'' comes originally from the assignment expression E1 = E2, in which the left operand E1 is required to be a (modifiable) lvalue. It is perhaps better considered as representing an object ''locator value''.

therefore, an expression consisting of a modifiable pointer variable can definitely act as lvalue, so is pointer to pointer and so on:

int i = 0;

int *p;
p = &i;        // 'p' is lvalue
int *q = p;    // 'p' is rvalue, lvalue conversion

*p = i;        // '*p' is lvalue
i = *p;        // '*p' is rvalue, lvalue conversion

int **pp;   
pp = &p;       // 'pp' is lvalue
int **qq = pp; // 'pp' is rvalue, lvalue conversion

int ***ppp;
ppp = &pp;     // 'ppp' is lvalue
int ***qqq = ppp; // 'ppp' is rvalue, lvalue conversion
like image 27
mzoz Avatar answered Oct 13 '22 16:10

mzoz