452 Chapter 10 Implementing Subprograms
main. The others have a return address to the function itself; these are for
the recursive calls.
Figure 10.8 shows the stack contents for the three times that execution
reaches position 2 in the function factorial. Position 2 is meant to be the
time after the return is executed but before the activation record has been
removed from the stack. Recall that the code for the function multiplies
the current value of the parameter n by the value returned by the recursive
call to the function. The first return from factorial returns the value 1.
The activation record instance for that activation has a value of 1 for its ver-
sion of the parameter n. The result from that multiplication, 1, is returned
to the second activation of factorial to be multiplied by its parameter
value for n, which is 2. This step returns the value 2 to the first activationFigure 10.7
Stack contents at position 1 in factorial
ARI = activation record instanceTop
Functional value
Parameter
Dynamic link
Return (to main)
LocalFirst ARI
for factorial
ARI
for main3 n?? valuenFunctional value
Parameter
Dynamic link
Return (to main)
LocalFirst ARI
for factorial
ARI
for main3??nTop
Functional value
Parameter
Dynamic link
Return (to factorial)Second ARI
for factorial
2?valuenFunctional value
Parameter
Dynamic link
Return (to main)
LocalFirst ARI
for factorialARI
for main3??nFunctional value
Parameter
Dynamic link
R eturn (to factorial)Second ARI
for factorial2?nTopvalueFunctional value
Parameter
Dynamic link
R eturn (to factorial)Third ARI
for factorial1?First callSecond callThird call