2.8 L-Values and R-Values

Expressions in C++ can evaluate to “l-values” or “r-values.” L-values are expressions that evaluate to a type other than void and that designate a variable.

L-values appear on the left side of an assignment statement (hence the “l” in l-value). Variables that would normally be l-values can be made nonmodifiable by using the const keyword; these may not appear on the left of an assignment statement.

Reference types are always l-values.

Some examples of correct and incorrect usages are:

i = 7; // Correct. A variable name, i, is an l-value.

7 = i; // Error. A constant, 7, is an r-value.

j * 4 = 7; // Error. The expression j * 4 yields an r-value.

*p = i; // Correct. A dereferenced pointer is an l-value.

const int ci = 7; // Declare a const variable.

ci = 9; // ci is a nonmodifiable l-value, so the

// assignment causes an error message to

// be generated.

((i < 3) ? i : // Correct. Conditional operator (? :)

j) = 7; // returns an l-value.

Note:

The previous example illustrates correct and incorrect usage when operators are not overloaded. By overloading operators, you can make an expression such as j * 4 an l-value.