L- and R-Values
L-Values is a object in storage that is addressable
- values that have names and are addressable
- modifiable if they are not constants
int x = 100; // x is an l-value
x = 1000;
x = 1000 + 20;
string name; // name is an l-value
name = "Frank";
R-Values: Non-L-Values
- R-Values are non-addressable and non-assignable!
- on the right-hand side of an assignment expression
- a literal
- a temporary, which is intended to be non-modifiable
100 = x; // 100 ist not an l-value
(1000 + 20) = x; // (1000 + 20) is NOT an l-value
string name;
name = "Frank";
"Frank" = name; // "Frank" is NOT an l-value
// examples
int x = 100; // 100 is an r-value
int y = x + 200; //(x+200) is an r-value
string name;
name = "Frank"; // "Frank" is an r-value
int max_num = max(20,30) // max(20,30) is an r-value
// -> ->
// r-values can be assigned to l-values explicitly
int x = 100;
int y = 0;
y = 100; // r-value 100 assgined to l-value y
x = x + y; // r-value (x+y) assigned to l-value x
references of l- and r-values (all references must be reference to l-values)
// example 1
int x = 100;
int &ref = x; // ref1 is reference to l-value
ref1 = 1000;
int &ref2 = 100; // Error, 100 is an r-value
// example 2
int square(int &n){
return n*n;
}
int num = 10;
square(num); // OK
square(5); // Error - can't reference r-value 5