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.

Lets look an example:

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

main();

Above, the main function is a global variable. The array x, however, 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.

Example:

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


What about when reference variables are accessed? Find its name in the current frame on the stack...if it doesn't exist, look in your global variables! Rather than duplicating the value as we would a primitive type, draw a pointer to the same value on the heap!

NOTE: will NEVER point to x directly...variables on the stack will never point to other variables on the stack! Arrows in environment diagrams will always point from the stack to the heap.

Example:

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: 

  • When we return a function, we are returning whatever value the variable name refers to on the heap! The function frame is "popped" (erased) off the stack once we are finished executing the function.
  • Void functions, while they do not return a value, will still be removed from the stack. This means that all of our pointers vanish...so what happens to their corresponding values on the heap? They will eventually be "garbage collected" and automatically removed :)