What happens is that the function is called again, under the control of the first call, and after that there are two invocations of factorial
active simultaneously (but the first one is waiting for the second one to return). Each of them has its own copy of n
: the subordinate invocation has n == 2
while the original invocation still has n == 3
. The subordinate invocation then calls itself another time, and so on, until there are four versions of the function in memory (but the first three are inactive, waiting for the last one to return).
The variable values and return addresses of all those invocations are kept on the call stack, and they disappear automatically when an invocation returns. (This is why a recursion that is too deeply nested can cause the phenomenon that this site was named after: the stack overflow.)
A good way to get your head around what really happens when a recursive function is called is to simulate the call stack with pen and paper, by writing down what versions of n
there are at any given time and what their values are. A call to factorial 3
is just the right size for that exercise.
return factorial(n-1) * n
. – richard Jul 26 '14 at 9:00