When a subroutine is called, the CPU stores execution context information on the call stack — a LIFO (Last In, First Out) data structure held in memory. Each entry on the call stack is called a stack frame.
| Item stored | Purpose |
|---|---|
| Return address | The memory address to resume execution when the subroutine finishes |
| Parameters | The values passed as arguments to the subroutine |
| Local variables | Variables declared inside the subroutine |
| Saved registers | CPU register values to be restored after the subroutine returns |
PUSH — When a subroutine is called, a new stack frame is pushed onto the top of the call stack.
POP — When the subroutine returns, its stack frame is popped off, restoring the previous frame and resuming from the stored return address.
Recursion is a programming technique where a subroutine calls itself. Each call creates a new stack frame, building up the call stack until the base case is reached.
FUNCTION factorial(n : INTEGER) RETURNS INTEGER
IF n = 0 THEN
RETURN 1 // Base case: 0! = 1
ELSE
RETURN n * factorial(n - 1) // Recursive case
ENDIF
ENDFUNCTION
Trace of factorial(3):
factorial(3) → 3 × factorial(2) factorial(2) → 2 × factorial(1) factorial(1) → 1 × factorial(0) factorial(0) → 1 // base case Unwinding: factorial(1) → 1 × 1 = 1 factorial(2) → 2 × 1 = 2 factorial(3) → 3 × 2 = 6
FUNCTION fib(n : INTEGER) RETURNS INTEGER
IF n ≤ 1 THEN
RETURN n
ELSE
RETURN fib(n-1) + fib(n-2)
ENDIF
ENDFUNCTION
Each recursive call adds a new stack frame. If the base case is never reached (or is reached too late), the call stack runs out of memory — this is called a stack overflow and causes a runtime error.
Causes of stack overflow from recursion:
| Feature | Recursion | Iteration |
|---|---|---|
| Code elegance | Often more concise and elegant for problems with naturally recursive structure (trees, graphs) | More verbose but explicit |
| Memory use | Builds up stack frames — higher memory overhead | Uses loop variable only — lower overhead |
| Speed | Slower due to repeated function call overhead | Generally faster |
| Risk | Stack overflow if base case not reached | Infinite loop if termination condition wrong |
| Readability | Natural for divide-and-conquer algorithms | Natural for counting and sequential tasks |
8 questions · instantly marked · AQA 7517 standard
| Term | Definition |
|---|
10 questions · 10 minutes