What is lvalue and rvalue in C++: Simple Explanation and Examples
lvalue refers to an object that has a persistent memory address and can appear on the left side of an assignment. An rvalue is a temporary value or literal that does not have a persistent address and usually appears on the right side of an assignment.How It Works
Think of an lvalue as a labeled box in your room where you can store things. You can point to this box anytime because it has a fixed place. In programming, this means an lvalue has a specific memory location and can be assigned new values.
On the other hand, an rvalue is like a temporary note you write and use immediately, then throw away. It doesn't have a fixed place to stay. In C++, rvalues are often temporary results of expressions or literals like numbers.
This distinction helps the compiler understand how to manage memory and optimize code, especially when dealing with references and move semantics.
Example
This example shows an lvalue as a variable that can be assigned to, and an rvalue as a temporary value used in an expression.
int main() { int x = 10; // 'x' is an lvalue int y = x + 5; // 'x + 5' is an rvalue x = 20; // 'x' on left side is lvalue // 15 = x; // Error: 15 is an rvalue, cannot be assigned to return 0; }
When to Use
Understanding lvalues and rvalues is important when writing efficient C++ code. Use lvalues when you need to store or modify data because they represent objects with a stable location.
Use rvalues when working with temporary data or values that don't need to be stored, such as results of calculations or literals. This knowledge is especially useful when using move semantics to optimize performance by transferring resources instead of copying.
Key Points
- lvalue has a memory address and can appear on the left side of an assignment.
- rvalue is a temporary value without a fixed address, usually on the right side.
- Only
lvaluescan be assigned new values. - Understanding these helps with references, pointers, and move semantics.