Expressions#
Based on C++ Primer, 5th ed. Chapter 4 (Expressions).
lvalues and rvalues#
Every expression in C++ is characterized by two independent properties: its type and its value category.
Core Distinction: Expression vs. Variable vs. Object#
- Expression: Possesses both a type (reference stripped) and a value category (lvalue, xvalue, prvalue). Value categories are strictly properties of expressions, never of variables.
- Variable: Possesses only a declared type (e.g.,
int,int&,int&&); a variable itself has no value category. When a variable’s name appears in code as an expression, that expression is evaluated as an lvalue (e.g., givenint &&rr = 10;, variablerrhas declared typeint&&, while the expressionrrhas typeintand value category lvalue). - Object vs. Variable:
- Object: A region of storage in memory holding a value.
- Variable: A named object or a named reference introduced by a declaration.
| Entity | Is Object? (Occupies Storage) | Is Variable? (Has Name) | Note |
|---|---|---|---|
x in int x = 10; | ✅ | ✅ | Named object in memory |
r in int &r = x; | ❌ | ✅ | Named reference (alias; unlike a pointer, r has no separate address of its own distinct from x, though used as an expression r designates x and is an lvalue with identity &r == &x) |
10 + 20 (temporary) | ✅ | ❌ | Unnamed temporary object |
Two Axes of Value Categories#
- Identity: Does the expression have an identifiable memory address (can we test whether two expressions designate the same entity with
&)? - Movable: Can the object’s resources be safely stolen or moved because it is expiring?
Value Categories Matrix (C++11)#
| Non-movable | Movable | |
|---|---|---|
| Has Identity | lvalue | xvalue (eXpiring value) |
| No Identity | (does not exist) | prvalue (pure rvalue) |
Value Category
/ \
glvalue rvalue
/ \ / \
lvalue xvalue prvalueThe 5 Value Categories#
1. Primary Categories#
- lvalue (Left Value): Has identity and cannot be moved from. Represents persistent objects or functions in memory.
- eg. Named variables (
x), dereference expressions (*ptr), prefix increment/decrement (++i), function calls returning lvalue references (std::cout << 1).
- eg. Named variables (
- prvalue (Pure Rvalue): Has no identity and can be moved from. Represents transient values computed on the fly. In C++17, a prvalue is an evaluation recipe that initializes an object.
- eg. Numeric/boolean literals (
42,true, excluding string literals), arithmetic expressions (a + b), function calls returning by value (GetPoint()).
- eg. Numeric/boolean literals (
- xvalue (eXpiring Value): Has identity and can be moved from. Designates an object nearing the end of its lifetime whose resources can be safely repurposed.
- eg. Cast to rvalue reference (
std::move(x)/static_cast<T&&>(x)), accessing a non-static member of an rvalue (GetPoint().x).
- eg. Cast to rvalue reference (
2. Composite Categories#
- glvalue (Generalized lvalue): lvalue + xvalue. Any expression whose evaluation determines the identity of an object or function.
- rvalue: prvalue + xvalue. Any expression eligible for move semantics.
Example#
std::string a = "hello";
std::string b = "world";
a; // lvalue: has persistent identity, cannot be moved from
a + b; // prvalue: transient computed value without persistent identity
std::move(a); // xvalue: designates existing object 'a', but marked movable
decltype Two-Step Deduction Rules and Expressions#
decltype(...) evaluates its operand using a two-step rule (Rule 1 → Rule 2):
- [Rule 1] Unparenthesized Variable / Member Name (
decltype(i),decltype(obj.x)):- Does not evaluate the expression’s value category (lvalue/rvalue); instead, it directly returns the exact declared type of that variable (
int i;→int).
- Does not evaluate the expression’s value category (lvalue/rvalue); instead, it directly returns the exact declared type of that variable (
- [Rule 2] All Other Expressions (
decltype(*p),decltype((i)),decltype(i + 1)):- Deduces the type based on the expression’s Value Category:
- lvalue expression: yields an lvalue reference (
T&). - xvalue expression: yields an rvalue reference (
T&&). - prvalue expression: yields the non-reference value type (
T).
- lvalue expression: yields an lvalue reference (
- Parenthesized Expression
(expr)Rule: Parentheses never alter the value category of the inner expressionexpr. Adding parentheses aroundiindecltype((i))simply disqualifies it from Rule 1 (bare variable name) so it falls through to Rule 2, where its lvalue category yieldsint&. By contrast,decltype((42))is a prvalue and yieldsint.
- Deduces the type based on the expression’s Value Category:
int i = 42;
int *p = &i;
decltype(i) r1 = 0; // int ([Rule 1] bare variable name -> declared type)
decltype((i)) r2 = i; // int& ([Rule 2] parenthesized (i) is an lvalue expression -> T&)
decltype(*p) r3 = i; // int& ([Rule 2] *p is an lvalue expression -> T&)
decltype(&p) r4 = &p; // int** ([Rule 2] &p is a prvalue expression -> T)
decltype(std::move(i)) r5 = std::move(i); // int&& ([Rule 2] std::move(i) is an xvalue expression -> T&&)
Reference Binding (T&, const T&, T&&) and Move Semantics#
For reference binding rules across lvalue and rvalue categories (why int &r = 42 is forbidden, temporary lifetime extension with const T&, and T&& rvalue references), why a named T&& variable is an lvalue expression, and how std::move and std::forward work, see Copy Elision & Move Semantics.
Operators and Value Categories#
For differences in operator return categories between C and C++, see lvalues and rvalues in C vs. C++.
1. Assignment Operator (=)#
- The LHS (left-hand operand) must be a modifiable lvalue.
- The result of an assignment is its LHS as an lvalue.
- The type of the result matches the type of the LHS.
- Assignment is right-associative (groups from right to left).
int a, b;
a = b = 10; // Parsed as a = (b = 10): valid in both C and C++ ((b = 10) sits on the RHS, where an rvalue is fine)
(a = b) = 42; // Compile error in C ((a = b) is an rvalue and cannot be the LHS), valid in C++ ((a = b) yields a as an lvalue)
In C, the result of an assignment is an rvalue (the value transferred), whereas in C++ it is an lvalue. Chained assignment
a = b = 10;still works in C because right-associativity groups it asa = (b = 10);, placing(b = 10)on the RHS. By contrast,(a = b) = 42;places the assignment result on the LHS, which fails in C and succeeds only in C++.
2. Increment and Decrement (++, --)#
- Prefix (
++i,--i): Increments/decrements the operand and returns the object itself as an lvalue (CLASS&). - Postfix (
i++,i--): Returns a copy of the object’s original value as an rvalue (CLASS), then modifies the operand. - For
CLASS& operator++()vs.CLASS operator++(int)overloading details, see Overloaded Operations: Prefix vs. Postfix.
int i = 0;
++i = 5; // Valid: prefix yields an lvalue
// i++ = 5; // Error: postfix yields an rvalue
Prefer prefix operators in C++ unless the original value is explicitly required. Prefix avoids creating temporary copies for complex types and iterators.
3. Member Access (->, .)#
- Arrow operator (
->): Requires a pointer operand and always yields an lvalue (ptr->mis equivalent to(*ptr).m). - Dot operator (
.):- Yields an lvalue if the object owning the member is an lvalue.
- Yields an rvalue (xvalue) if the object owning the member is an rvalue.
struct Point { int x, y; };
Point p{1, 2};
Point GetPoint() { return {3, 4}; }
p.x; // lvalue (p is an lvalue)
GetPoint().x; // xvalue (member of an rvalue temporary)
4. Conditional Operator (?:)#
The conditional operator (cond ? expr1 : expr2) evaluates to:
- An lvalue if both
expr1andexpr2are lvalues of the same type (or convert to a common lvalue type). - An rvalue otherwise.
int a = 10, b = 20;
((a < b) ? a : b) = 30; // Valid in C++: yields an lvalue (assigns 30 to a)
int x = (true ? 1 : 2); // Yields an rvalue
In C,
?:always yields an rvalue regardless of operand categories.