L-values vs R-values
What you'll learn: How to identify which parts of a C statement represent a memory location and which represent a temporary value.
In C, the assignment operator (=) isn't just a mathematical sign of equality; it is an instruction to move data. To understand how this works, you need to understand the two "sides" of the operation: the L-value and the R-value.
The Mailbox Analogy
Think of an L-value (Left-value) as a physical mailbox. It has a specific address on a street, and it is a container that can hold a letter. Because it is a permanent location, you can point to it and say, "Put the data here."
Think of an R-value (Right-value) as the letter itself. It is the information or the result of a calculation. By itself, a letter doesn't have a permanent home; it’s just data passing through until you put it inside a mailbox.
Identifying the Sides
The names come from where these items typically sit in relation to the equals sign:
- L-values (Left side): These are expressions that refer to a memory location. The most common L-value is a variable name. Because they represent a "container," you can assign a value to them.
- R-values (Right side): These are the actual data values. They can be numbers (like
5), character literals (like'A'), or the result of a calculation (likex + 10).
int x; // 'x' is an L-value (a memory location)
x = 10; // Valid: Moving the R-value '10' into the L-value 'x'
int y = x; // Valid: An L-value can act as an R-value to provide its data
// 10 = x; // ERROR: '10' is an R-value. You can't store data inside the number 10!
Why It Matters
You will often encounter compiler errors saying "L-value required." This is the computer's way of telling you that you're trying to shove data into something that isn't a storage container. For example, if you try to write (x + 1) = 5;, the computer complains because x + 1 is just a temporary result (a letter), not a permanent mailbox where the 5 can live.
Key takeaway
An L-value is a storage location (a container), while an R-value is the data being stored (the contents).