Assuming the definition:
int i = 10;
int *p = &i;
Why is *p a valid lvalue here:
*p+=10;
Shouldn't *p evaluate to the value of the int stored at &i, ie. 10, and hence generate a "Not an lvalue" error?
An lvalue is an expression that refers to a region of storage that can be manipulated.
*p
is such an expression that refers to a region of storage. This is different than say 10+=10;
because 10
doesn't refer to a region of storage like a variable would.
I believe you are confused with the definition of p
. p
is, in fact, a variable of type pointer to int, and its value is initialized to the address of i
.
Nonetheless, *p
is a valid lvalue as well - a valid expression to a storage location.
In very simple words, pointers point to an object (in a general, non OOP sense), not to the contents of that object. So yes, a dereferenced pointer is a valid lvalue.
In very low level terms. A pointer is nothing but a memory address, a dereferenced pointer is the memory at that address.
Shouldn't
*p
evaluate to the value of the int stored at&i
, ie. 10, and hence generate a "Not an lvalue" error?
In simple words,
*
means "value at address".
*p
means "value at address given by the value of p
".
*p = 10;
means "set 10 as the value at address given by the value of p
".
lvalue is an expression that refers to an object stored somewhere in the memory. *p
is also an expression that refers to an object stored at location p
.
Semantics
...
- The unary
*
operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ''pointer to type'', the result has type ''type''. If an invalid value has been assigned to the pointer, the behavior of the unary*
operator is undefined
I.e. with
int i = 10;
int *p = &i;
the result of *p
is an lvalue that designates the object i
.
Therefore *p += 10
works, as it is an lvalue.
Now, if an lvalue were used in a context where the object itself is needed, it would be converted to the value stored in the designated object. This is called the lvalue conversion, and the resulting value of course isn't an lvalue anymore (C11 6.3.2.1p2).
来源:https://stackoverflow.com/questions/4773839/is-a-dereferenced-pointer-a-valid-lvalue