Lvalues and Rvalues

This lesson explains the difference between the lvalues and rvalues, limitations of rvalues and how both can be passed as parameters to functions.

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:

Press + to interact
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;
}
...
Access this course and 1400+ top-rated courses and projects.