Concepts of Programming Languages

(Sean Pound) #1

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 activation

Figure 10.7


Stack contents at position 1 in factorial


ARI = activation record instance

Top
Functional value
Parameter
Dynamic link
Return (to main)
Local

First ARI
for factorial


ARI
for main

3 n

?

? value

n

Functional value
Parameter
Dynamic link
Return (to main)
Local

First ARI
for factorial


ARI
for main

3

?

?

n

Top
Functional value
Parameter
Dynamic link
Return (to factorial)

Second ARI
for factorial


2

?

value

n

Functional value
Parameter
Dynamic link
Return (to main)
Local

First ARI
for factorial

ARI
for main

3

?

?

n

Functional value
Parameter
Dynamic link
R eturn (to factorial)

Second ARI
for factorial

2

?

n

Top

value

Functional value
Parameter
Dynamic link
R eturn (to factorial)

Third ARI
for factorial

1

?

First call

Second call

Third call
Free download pdf