Reference Variables

This lesson explains some terminology used with reference variables and the use of the ref keyword.

Terminology #

We have frequently used the phrase “provide access to” throughout the course. For example, slices and associative arrays do not own any elements but provide access to elements that are owned by the D runtime. Another phrase, identical in meaning, is “being a reference of” as in “slices are references of zero or more elements.” This is sometimes also used as “this slice references two elements.” Finally, the act of accessing a value through a reference is called dereferencing.

Reference variables are variables that act as aliases of other variables. Although they look like and are used as variables, they do not have values and addresses in memory. Modifications made on a reference variable change the value of the actual variable.

So far, we have already used reference variables in two contexts:

ref in foreach loops: #

The ref keyword makes the loop variable the actual element that corresponds to that iteration. When the ref keyword is not used, the loop variable is a copy of the actual element.
This can be demonstrated by the & operator as well. If their addresses are the same, two variables would be referencing the same value (or the same element in this case):

Get hands-on with 1200+ tech skills courses.