Skip to main content
Be Bitwise

Nested Function Calls

Call a function that calls another function. Watch the stack grow with return addresses as calls nest, then unwind as each function returns.

When function A calls function B which calls function C, each CALL pushes a return address onto the stack. The stack accumulates return addresses in the order calls were made, and RET pops them in reverse order. This stack-based bookkeeping is what lets the CPU handle arbitrarily deep nesting — recursion, callback chains, and complex call graphs all rely on the same push-on-call, pop-on-return mechanism.

Simulator

Loading simulator...

Walkthrough Guide

  1. 1

    Begin the outer call

    Do this: Step through MOV R0, #2 then CALL add_three

    Watch for: R0 = 2. CALL pushes the return address and jumps to add_three. SP decrements

    The first CALL saves where to return (the HALT instruction) on the stack and jumps to add_three. One return address is now on the stack.

  2. 2

    Nested call from within add_three

    Do this: Step through CALL add_two inside add_three

    Watch for: A second return address is pushed onto the stack. SP decrements again. PC jumps to add_two

    add_three immediately calls add_two, pushing a second return address. The stack now holds two return addresses — this is the deepest point of nesting.

  3. 3

    Execute the inner function and return

    Do this: Step through ADD R0, #2 then RET in add_two

    Watch for: R0 goes from 2 to 4. RET pops the top return address and jumps back into add_three. SP increments

    add_two does its work and returns. RET pops the most recent return address (the one pushed by the CALL in add_three), resuming inside add_three.

  4. 4

    Complete the outer function and return

    Do this: Step through ADD R0, #1 then RET in add_three

    Watch for: R0 goes from 4 to 5. RET pops the original return address and jumps back to HALT. SP returns to its starting value

    add_three finishes and returns to the original caller. The stack unwinds completely — both return addresses have been popped in LIFO order. R0 = 5: 2 + 2 + 1.

Objectives

  • •See CALL push a return address and jump to add_three
  • •Watch a second return address get pushed when add_three calls add_two
  • •Notice the stack holds two return addresses at the deepest point
  • •Watch RET pop addresses in reverse order as the call stack unwinds

Hints

  • Watch SP and the memory near the top of address space - each CALL pushes one return address, each RET pops one