I read this sentence in a book: C primer Plus (The sixth edition) Since I read the Chinese version, I can only translate the Chinese version of the book as follows.
Rvalue: refers to a value that can be assigned to a modifiable left value and is not itself an lvalue.
Is this true or false? I feel like there's something wrong with that sentence. My opinion is as follows:
#include <stdio.h>
int main(void) {
int a = 3; ok beacase 3 is constent
int b = 3 + 4; ok beacase 3 is expression
int c = a; ? a is rvalue
/*
a is an rvalue, isn't that inconsistent with what we said before and not an lvalue itself? I hadn't noticed this basic problem before. I wish someone could help me. Ask sb. to do STH.
*/
return 0;
}
a
itself should be an lvalue
. Isn't that so?
Rvalue: refers to a value that can be assigned to a modifiable left value and is not itself an lvalue.
Is this true or false? I feel like there's something wrong with that sentence.
The idea conveyed by the English sentence presented is accurate, though the wording is awkward. However, you seem to have taken the incorrect idea from it that only rvalues can appear as the right-hand operand of an assignment operation. Perhaps you're ignoring the "and is not itself an lvalue" part? That's by far the more important criterion.
int c = a; ? a is rvalue /* a is an rvalue, isn't that inconsistent with what we said before and not an lvalue itself? I hadn't noticed this basic problem
before. I wish someone could help me. Ask sb. to do STH. */
a
is an lvalue because it designates an object. Objects have associated storage. It is not an rvalue, because, as your definition specifically says, lvalues are not rvalues.
Although the terms "lvalue" and "rvalue" are derived from the idea of what kinds of expressions can appear on the left and right sides of an assignment, that really doesn't get to the core idea:
An lvalue expression is one that (potentially) designates an object, as I said above. A variable name, an array subscription expression (array[1]
), a structure or union member selection (s.member
), and a pointer derference (*p
) are all examples.
An rvalue, on the other hand, is an expression that is not an lvalue. Such an expression does not designate an object, only a value. Some would insist that it not be a void
expression. Such a value is ephemeral in that it exists only in the context of the full expression in which it appears. Integer and floating constants; arithmetic, relational, sizeof
, and alignof
expressions; and function return values are among the common kinds of rvalues in C.
Any expression of suitable data type may appear as the right-hand operand of an assignment. That doesn't speak to whether the expression is an lvalue or an rvalue.