INTRODUCING LVALUES AND RVALUES

Every expression in C++ results in either an lvalue or an rvalue (sometimes written l-value and r-value and pronounced like that). An lvalue refers to an address in memory in which something is stored on an ongoing basis. An rvalue, on the other hand, is the result of an expression that is stored transiently. An lvalue is so called because any expression that results in an lvalue can appear on the left of the equals sign in an assignment statement. If the result of an expression is not an lvalue, it is an rvalue.

Consider the following statements:

int a(0), b(1), c(2);
a = b + c;
b = ++a;
c = a++;

The first statement declares the variables a, b, and c to be of type int and initializes them to 0, 1, and 2, respectively. In the second statement, the expression b + c is evaluated and the result is stored in the variable a. The result of evaluating the expression b + c is stored temporarily in a memory location and the value is copied from this location to a. Once execution of the statement is complete, the memory location holding the result of evaluating b + c is discarded. Thus, the result of evaluating the expression b + c is an rvalue.

In the third statement, the expression ++a is an lvalue because its result is a after its value is incremented. The expression a++ in the third statement is an rvalue because it stores the value of a temporarily as the result of the expression and then increments a.

An expression that consists of a single named variable ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.