[   ^ to index...   |   <-- previous   |   next -->   ]

How recursion works

Every time a procedure is called, it gets a fresh activation record on the call stack.

activation record
is a chunk of memory allocated to hold the local variables and parameters of that procedure
call stack
is a region of memory set aside to hold activation records. Activation records are placed onto the stack, and removed from the stack, in strict LIFO order (which is why it is a stack).

Here's a picture of the computation of add(3, 11)

1:

add(3, 11)
return 1 + add(2, 11)

2:

add(3, 11)
return 1 + add(2, 11)
add(2, 11)
return 1 + add(1, 11)

3:

add(3, 11)
return 1 + add(2, 11)
add(2, 11)
return 1 + add(1, 11)
add(1, 11)
return 1 + add(0, 11)

4:

add(3, 11)
return 1 + add(2, 11)
add(2, 11)
return 1 + add(1, 11)
add(1, 11)
return 1 + add(0, 11)
add(0, 11)
return 11

5:

add(3, 11)
return 1 + add(2, 11)
add(2, 11)
return 1 + add(1, 11)
add(1, 11)
return 1 + 11

6:

add(3, 11)
return 1 + add(2, 11)
add(2, 11)
return 1 + 12

7:

add(3, 11)
return 1 + 13

8:

14

Last modified: Thu Jul 6 13:55:31 PDT 2000