lvalue and rvalue
Overview
| lvalue | rvalue | |
|---|---|---|
| Description | Refers to a memory location | Value resulting from an expression |
| Position | Left of '=' | Right of '=' |
| Name | L = Left/Locator (Memory) | R = RIght |
| Can assign | ✅ | ❌ |
| Can read | ✅ | ✅ |
| Others | Has name/variable/address | |
| Examples ( int a,b,c) |
Examples
Legal usage
int a = 1, b = 2, c = 3;
// === Normal use ===
a = b + c; // a - lvalue, b + c -
a = 7; // a - lvalue, 7 - rvalue
// === Weird but still able to compile ===
// Breakdown:
// - (b = c) -> b assigned to c, returns a rvalue
// - c = a + (return value)
// - NOTE: This is different from: "c = a + b = c;" which is illegal
c = a + (b = c);
Illegal usage
int a = 1, b = 2, c = 3;
// === Clearly wrong ===
// === Less clearly wrong
// Operator precedence: '+' has higher precedence than '='
c = a + b = c;
// Why? (a = b) => rvalue, which can't be assigned to c
(a = b) = c;
(((a = b) = c) = 5);
Links
- Operator precedence - NOTE: Equal is the least priority.
- Cherno video (More on C++)