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()
is called with an argument
greater than one, it calls itself, fact()
, with a new argument.
This works because the data needed for the first activation offact()
is pushed onto
the stack.
When that activation gets control again that data is popped from the stack.
This process is illustrated at right.
Each bead on the activation chain represents an activation of a subroutine. The label on a downward arc is the argument to the subroutine. The label on an upward ard 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
.