In C, is there a way to identify the rvalues and lvalues ?
Some of them are easy to identity say, in an assignment, the left value is lvalue and the value in the right is rvalue.
But other scenarios, identification with such a rule is difficult.
For example : *p++
and i++
(where p is a pointer to integer and i is an integer) - how to identify whether it is an rvalue or lvalue ?
The context is ++*p++
works while ++i++
does not since i++
is an rvalue (as told by serious guys).
How to identify rvalue and lvalue in an expression?
lvalue (from left-hand side (LHS) value) in something that refers to a memory (or register) storage and that you can assign values to. *p++
is an lvalue since it is a dereferenced pointer (i.e. refers to the location in memory that ptr
points to while the value of ptr
itself is the address of that location) and ++*ptr++
actually means: *ptr = *ptr + 1; ptr = ptr + 1;
- it increments the value pointed to by ptr
and then increments the pointer value itself. i++
is not an lvalue since it is the value of i
incremented by 1 and does not refer to a location in memory. You can think of such values as final - they cannot be further modified and can only be used as values to assign to lvalues. That's why they are called rvalues (from right-hand side (RHS) value).
LHS and RHS refer to both sides of the assignment expression A = B;
. A
is the LHS and B
is the RHS.