Imagine you have a toy box.
- Lvalue: Think of the toy box itself. It’s a place where you can keep your toys. You can put a toy in the box, take one out, or replace one toy with another. In C++, an lvalue is like this box — it’s a location in memory where a value is stored, and you can change what’s stored there.
- Example:
int my_number = 5; - Here,
my_numberis an lvalue because it’s like the toy box where the number 5 is stored. You can changemy_numberlater, like putting a different toy in the box (e.g.,my_number = 10;).
- Example:
- Rvalue: Now, think of a toy you’re holding in your hand. It’s a specific toy that you can use to play with, but you can’t change that toy into something else on the spot. In C++, an rvalue is like this toy— it’s a value that exists temporarily and can’t be directly modified.
- Example:
5 + 3 - The result of this (which is 8) is an rvalue. It’s like the toy you just created by combining parts (5 and 3), but you can’t change this 8 directly; you can’t say “8 = 10”. It’s just a value you use.
- Example:
Key Points to Remember:
- Lvalues can appear on the left side of an assignment (
=). They represent things that can be modified or assigned to. - Rvalues typically appear on the right side of an assignment. They represent temporary values that can’t be assigned to directly.
Simplified Summary:
- Lvalues are like toy boxes: You can store and change what’s inside.
- Rvalues are like toys: You can use them, but you can’t change them directly.