Using the Stack for Parameter Passing
In Session 3, we discussed the lifetime of local variables and how the stack is used to manage this lifetime:
-
When a function is called, all local variables for that function call are newly allocated on the stack.
-
When the function exits, the local variables are removed from the stack.
Let's simulate this behavior using our own stack based on the following example, where the function foo only has one local variable, the function parameter n:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | @ <stdio.hdr> fn foo(n: int) { printf("entered foo with n = %d\n", n); if (n > 1) { foo(n - 1); } printf("leaving foo with n = %d\n", n); } fn main() { foo(3); } |
The stack usage for this program can be described with this diagram:

Perform the following changes to mimic how local variables are allocated and released on the stack when a function is called and exited:
-
Modify a function call like foo(3) into two instructions:
1 2
push(3); // Push the parameter onto the stack foo(); // Then call the function
-
So, the declaration of the function foo is now parameterless. Instead of accessing n, we'll access the top element of the stack using top().
-
Before exiting the function foo, remove the parameter from the stack using a pop operation.
-
Use the info function to display the stack when entering and exiting the foo function.