Search⌘ K
AI Features

Lvalues and Rvalues

Explore the concepts of lvalues and rvalues in D programming to understand how expressions are classified, their limitations, and their impact on function parameters. This lesson explains the difference between values with memory addresses and temporary results, and introduces how auto ref parameters handle them in function templates.

The difference between lvalues and rvalues

The value of every expression is classified as either an lvalue or an rvalue. A simple way of differentiating the two is thinking of lvalues as actual variables (including elements of arrays and associative arrays) and rvalues as temporary results of expressions (including literals).
As a demonstration, the first writeln() expression below uses only values, and the other one uses only rvalues:

D
import std.stdio;
void main() {
int i;
immutable(int) imm;
auto arr = [ 1 ];
auto aa = [ 10 : "ten" ];
/* All of the following arguments are lvalues. */
writeln(i, // mutable variable
imm, // immutable variable
arr, // array
arr[0], // array element
aa[10]); // associative array element
// etc.
enum message = "hello";
/* All of the following arguments are rvalues. */
writeln(42, // a literal
message, // a manifest constant
i + 1, // a temporary value
calculate(i)); // return value of a function
// etc.
}
int calculate(int i) {
return i * 2;
}

Limitations of rvalues

Compared to lvalues, rvalues have the following three ...