✏️ Explanatory Question

What is l-value and r-value?

👁 1,385 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

What is an l-value and r-value?

In programming, especially when working with assignment statements, the terms l-value and r-value are used to describe the roles played by expressions on the left-hand side and right-hand side of an assignment operator (=).

l-value

An l-value (left value) is an expression that refers to a specific memory location and can generally appear on the left-hand side of an assignment statement. In simple terms, an l-value identifies the destination where a value can be stored.

A variable is a common example of an l-value because it represents a modifiable storage location.

x = 10

In this statement, x is the l-value because it represents the location where the value 10 is stored.

r-value

An r-value (right value) is an expression that provides a value to be assigned, used, or evaluated. It normally appears on the right-hand side of an assignment operator.

In the following example:

x = 10

10 is the r-value because it is the value that is assigned to x.

Example

a = 20
b = a + 5

In the first statement, a is the l-value and 20 is the r-value.

In the second statement, b is the l-value, while a + 5 is the r-value because the expression is evaluated to produce a value that is assigned to b.

Important Difference

l-value r-value
Usually appears on the left side of an assignment. Usually appears on the right side of an assignment.
Represents a storage location. Represents a value or expression that produces a value.
Can generally receive a value. Provides a value to be used or assigned.
Example: x Example: 10, x + 5

Example of an Invalid Assignment

10 = x

This is invalid because 10 is a literal value and does not represent a modifiable storage location. Therefore, it cannot act as an l-value in a normal assignment.

Similarly, an expression such as x + 5 generally cannot be used as the destination of an assignment because it produces a value rather than identifying a modifiable storage location.

In Simple Terms

You can remember the difference using this simple rule:

l-value = Where the value is stored
r-value = The value that is stored or used

Therefore, in total = price + tax, total is the l-value, while price + tax is the r-value.