Search⌘ K
AI Features

Parameter Qualifiers: ref, auto ref and inout

Explore how to use parameter qualifiers ref auto ref and inout in D programming. Understand their roles in passing variables by reference, handling templates, and managing mutability in function parameters and return types.

We'll cover the following...

ref

This keyword allows passing a variable by reference even though it would normally be passed as a copy (i.e. by value).

For the reduceEnergy() function that we saw earlier, to modify the original variable, it must take its parameter as ref:

D
import std.stdio;
void reduceEnergy(ref double e) {
e /= 4;
}
void main() {
double energy = 100;
reduceEnergy(energy);
writeln("New energy: ", energy);
}

This time, the modification that is made to the parameter changes the original variable in main().
As can be seen, ref parameters can be used both as input and output. ref parameters can also be thought of as aliases of the original variables. The function parameter e above is an alias of the variable energy in main().

Similar to out parameters, ref ...