Functions and the call stack – parameters, return values and scope

Computer ScienceAlgorithms & Problem SolvingAges 15–16

Loading…

Use with my class ✨ Customize with AI Report a problem

Step through programs that call procedures and functions and watch each call push a stack frame: arguments bound to parameters, local variables, and the return value passed back to the calling line. Compare local and global variables, pass by value and by reference, and recursion in Python or pseudocode. A library mode lets you call built-in routines to explore signatures and abstraction.

Lesson: Subroutines: procedures, functions, parameters and scope

What it shows

A subroutine is a named block of code that can be called many times. When it is called, the computer pushes a stack frame holding its parameters and local variables; the arguments are bound to the parameters, and return passes a value back and pops the frame. Local variables exist only during the call and can hide global variables with the same name. Recursion stacks many frames of the same function. Library routines hide their code behind a signature, which is how programs are decomposed into modules and APIs.

How to use

Choose an Example and a Language, then press Step to run one line at a time or Run to play the program at the chosen Speed. Watch the call stack, the notes under What happened in this step and the stack depth chart. Press Edit to change the code. Switch to Library routines, pick a Routine, type the arguments and press Call.

Parameters you can change

  • Mode Trace a program, Library routines
  • Example Parameters and return values, Local and global variables, Functions calling functions, Procedures and functions, Recursion (factorial), Passing by value and by reference
  • Language Python, Pseudocode
  • Run speed 0.5–10 steps/s

Questions to explore

  1. In the call area(w, 3), which values are the arguments and which names are the parameters?
  2. Why does print(count) in the main program still show 10 after double(3) has run?
  3. How many frames are on the call stack when factorial(4) reaches its base case?