fact(5) == 5*fact(4) == 5*( 4*fact(3) ) == 5*( 4*( 3*fact(2)) ) == 5*( 4*( 3*(2*fact(1))) ) == 5*( 4*( 3*(2*1)) ) == 5*4*3*2*1 == 120
If
the subroutine fact()
fact()
fact()
When the first activation gets control again, its data is available at the top of the stack. This process is illustrated at right. Each activation is represented as a green circle. Each activation works with its own data in its own stack frame. The activations do not interfere with each other.
# int fact( int n ) # { # if ( n <= 1 ) # return 1; # else # return n*fact(n-1); # }
Each bead on the activation chain represents an activation of a subroutine. The label on a downward arc is the argument to an activation. The label on an upward arc is the returned value.
Each bead on the activation chain corresponds to one stack frame.
The picture of the stack shows what it looks like when
the activation fact(1)
is running.
When the value 120 is returned to main
,
only main
is active, the stack
contains only its stack frame, and the activation chain consists only of
main
.