Comp 110 Local Reference Variables

What is a Local Reference Variable?

Reference variables are variables (in the stack) that hold a reference to objects/arrays (on the heap).

Local variables are variables defined within a particular function, and as a result can only be accessed within the scope of that function.

Together, these make local reference variables. Local reference variables will be found throughout our program, but by definition a variable in the globals frame is NOT a local variable.

Let's look an example:

export let main = async () => {
  let x: number[];
};

main();

The array x  is a local variable, as it is declared within the main function. Since it is an array, it is also a reference variable -- meaning it stores a reference (sometimes called a pointer) to its value, which is stored on the heap.

When we assign elements to arrays, we use name resolution to find the correct variable on the stack and follow the pointer to its heap value.

export let main = async () => {
     let x:number[];
     x = [];
     x[0] = 0;
}
main();

export let main = async () => {
     let x:number[];
     x = [];
     x[0] = 0;
     let y = x;
}
main();

// we are accessing the reference variable x and assigning it to y
// x exists in the current 'main' frame
// we draw a pointer from a new variable on the stack 'y' to the heap value referenced by 'x'

What not to do:

To access elements of an array via index, use name resolution to find the correct variable on the stack, follow the pointer, and lookup the element at that index!

NOTES: 

  • This means that when something changes in 'x,' 'y' is also changing!