Programming Fundamentals/Lvalue and Rvalue

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Overview[edit | edit source]

Some programming languages use the idea of L-values and R-values, deriving from the typical mode of evaluation on the left and right-hand side of an assignment statement. An L-value refers to an object that persists beyond a single expression. An R-value is a temporary value that does not persist beyond the expression that uses it.[1]

Discussion[edit | edit source]

L-value and R-value refer to the left and right side of the assignment operator. The L-value (pronounced: L value) concept refers to the requirement that the operand on the left side of the assignment operator is modifiable, usually a variable. R-value concept pulls or fetches the value of the expression or operand on the right side of the assignment operator. Some examples:

age = 39

The value 39 is pulled or fetched (R-value) and stored into the variable named age (L-value); destroying the value previously stored in that variable.

voting_age = 18
age = voting_age

If the expression has a variable or named constant on the right side of the assignment operator, it would pull or fetch the value stored in the variable or constant. The value 18 is pulled or fetched from the variable named voting_age and stored into the variable named age.

age < 17

If the expression is a test expression or Boolean expression, the concept is still an R-value. The value in the identifier named age is pulled or fetched and used in the relational comparison of less than.

JACK_BENNYS_AGE = 39
JACK_BENNYS_AGE = 65;

This is illegal because the identifier JACK_BENNYS_AGE does not have L-value properties. It is not a modifiable data object, because it is a constant.

Some uses of the L-value and R-value can be confusing in languages that support increment and decrement operators. Consider:

oldest = 55
age = oldest++

Postfix increment says to use my existing value then when you are done with the other operators; increment me. Thus, the first use of the oldest variable is an R-value context where the existing value of 55 is pulled or fetched and then assigned to the variable age; an L-value context. The second use of the oldest variable is an L-value context wherein the value of the oldest is incremented from 55 to 56.

Key Terms[edit | edit source]

Lvalue
The requirement that the operand on the left side of the assignment operator is modifiable, usually a variable.
Rvalue
Pulls or fetches the value stored in a variable or constant.

References[edit | edit source]