In the following code, is *a
an rvalue or an lvalue?
#include <stdio.h>
void main()
{
int b=2;
int *a=NULL;
a=&b;
*a=3;
printf("%d",*a);
}
In the following code, is *a
an rvalue or an lvalue?
#include <stdio.h>
void main()
{
int b=2;
int *a=NULL;
a=&b;
*a=3;
printf("%d",*a);
}
As exposed in http://en.wikipedia.org/wiki/Value_%28computer_science%29 :
Lvalues have memory addresses that are programmatically accessible to the running program (e.g., via some address-of–operator like "&" in C/C++), meaning that they are variables or dereferenced references to a certain memory location. Rvalues can be lvalues (see below) or non-lvalues
So, *a is an lvalue
It is an l-value and can be used in a context of r-value. See the example;
int i, j, *p, *q;
p = &i;
q = &j;
*p = 1; // *p is l-value
*q = 2; // *q is l-value
*p = *q // *q is r-value
As pointed by Charles Bailey in his comment:- The sub-expression *q
is still an l-value, it undergoes an l-value to r-value conversion because it is used in a context where an r-value is required.
Now one may think Why *q
is still l-value?
Because by definition of r-value an r-value is a temporary value that does not persist beyond the expression that uses it.
In this case value of *q
is persists beyond the expression *p = *q
.
NOTE:
" * " operator--the deference/indirection operator -- operates on pointer variable, and returns an l-value equivalent to the value at pointer address.
According to K&R 2nd edition on p197 §A5:
...an lvalue is an expression referring to an object... for example, if
E
is an expression of pointer type, then*E
is an lvalue expression referring to the object to whichE
points.
additionally Scott Meyers in his book Effective Modern C++, Introduction - Terminology and Conventions puts another simpler way to determine lvalue/rvalue:
A useful heuristic to determine whether an expression is an lvalue is to ask if you can take its address. If you can, it typically is. If you can’t, it’s usually an rvalue. A nice feature of this heuristic is that it helps you remember that the type of an expression is independent of whether the expression is an lvalue or an rvalue.
therefore, when *p
expression appears on the left side it's a lvalue
, the right side rvalue
.