Lvalues vs.
Rvalues in C++
Understand the two fundamental value categories that govern how C++ handles memory, assignment, and expression evaluation.
Why Do Value Categories Matter?
Every expression in C++ has a type and a value category. The type tells the compiler what data you have. The value category tells the compiler where that data lives and what you can do with it.
If you have ever seen an error like "cannot take address of an rvalue" or "cannot assign to a temporary", understanding lvalues and rvalues is the key to decoding it.
What Is an Lvalue?
An lvalue (historically "left value") is an expression that refers to a persistent memory location. It has an identifiable address that your program can use again and again.
What Is an Rvalue?
An rvalue (historically "right value") is an expression that does not persist beyond the statement that creates it. It is a temporary: no lasting address you can point to.
The Core Rule
Common Examples of Each
Array elements: arr[2]
Dereferenced pointers: *ptr
Member access: obj.data
Prefix increment: ++x
Arithmetic results: x + 1
Function returns (by value): getVal()
Casts: static_cast<int>(y)
Postfix increment: x++
Left Side vs. Right Side of Assignment
However, do not think "lvalue = left side only." Lvalues can also appear on the right side. In y = x, the lvalue x sits on the right. It just means "read the value stored at x."
Lvalue References
An lvalue reference (declared with &) can only bind to an lvalue. This is the "regular" reference you already know.
Rvalue References (C++11)
C++11 introduced rvalue references (declared with &&) that can bind specifically to rvalues. This is the foundation of move semantics.
Reference Binding Chart
How to Identify Value Categories
&expr and have it compile? If yes, it is an lvalue. If no, it is an rvalue.Example 1: Simple Assignments
Example 2: Function Returns
Example 3: Tricky Cases
Common Mistakes
Lvalue vs. Rvalue Summary
| Property | Lvalue | Rvalue |
|---|---|---|
| Has a name? | Usually yes | No |
| Has an address? | Yes (& works) | No (& fails) |
| Persists after statement? | Yes | No (temporary) |
| Can assign to? | Yes (if non-const) | No |
| Binds to \(\texttt{T\&}\)? | Yes | No |
| Binds to \(\texttt{T\&\&}\)? | No | Yes |
| Binds to \(\texttt{const T\&}\)? | Yes | Yes |
| Example | x, arr[0], *ptr | 42, x+1, func() |
Question 1 of 5
Given int x = 10;, which of the following expressions is an rvalue?
Question 2 of 5
Which statement will cause a compilation error?
Question 3 of 5
A function declared as int getValue() (returning by value). The expression getValue() is:
Question 4 of 5
Given \(\texttt{int\&\& rref = 5 + 3;}\), what is the value category of the expression rref itself?
Question 5 of 5
Which of the following is true about \(\texttt{const T\&}\)?