Comp 110 Reference Parameters

Reference Parameters

Reference parameters are just what they sound like -- parameters that are reference types! Why does this matter/make them different than parameters that are just primitive types (i.e. string, number, boolean) ?

Reference parameters are special because when the parameters are modified or changed in the body of the function they belong to, the corresponding arguments used to originally call the function are modified. 

We should think about functions as a way to pass data from one place in our program to another. This is especially important when the arguments/parameters are reference types because we can call a function and send data elsewhere in our program to be manipulated, and the result is a modification of our original data. Lets take a look at a simple example:

export let main = async() => {
    let arr1 = [1, 2, 5];
    let x = 2;
    changeTo3(arr1, x);
    print(arr1);
};
export let changeTo3(a: number[], b: number): void => {
    a[i] = 3;
};
main();

The changeTo3 function takes in an array and a number, and changes the element at that index to be 3. This may seem trivial, but something magical is happening here. If we draw out the environment diagram for this program, we will see that since arr1 is a reference being passed to the changeTo3 function and assigned to aarr1 and a are going to be pointing to the same place in the heap. 


This means that when one a in changeTo3 is modified, so is arr1. Therefore the resulting output when this program runs is [1, 2, 3]. 

As soon as the call to changeTo3 is over, variable a is 'popped' along with that entire stack frame. However, our arr1 array remains modified!