Who gets a finished call’s answer?

Where a return goes

Theo Brooks

How recursion works

Each result fills just its caller’s blank, until factorial of 2 gives the original caller its answer: 2.

Transcript

The 1 is leaving factorial of 0, but where does it go when both multiplications are waiting for a number?

That 1 is the answer from factorial of 0, but it’s not the answer to your original request. Each call has its own row to remember its input and where it paused, and that record is its call frame. The call frame for factorial of 1 keeps its multiplication separate from the one below. Now the frame for factorial of 0 leaves as its 1 fills the blank in factorial of 1. So the top call is done, factorial of 1 has 1 times 1, and factorial of 2 still needs a number to multiply its 2 by. Factorial of 1 is the immediate caller because it asked for factorial of 0 directly. Only the blank in the immediate caller needed that answer. That 1 is the return value, the answer a finished call gives back to its caller. Factorial of 2 is waiting for a different call’s return value because it asked for factorial of 1.

Look at the first multiplication: the 1 on the left is the number this call kept, and the 1 on the right is the answer it needed. So factorial of 1 can finish: 1 times 1 equals 1. It’s the same number, but now it’s this call’s own answer.

Now the frame for factorial of 1 leaves as its 1 fills the blank in factorial of 2. So factorial of 1 is done, and factorial of 2 has 2 times 1. Only the blank needed that answer, because this call already had its own 2.

Now factorial of 2 can finish its multiplication: 2 times 1 equals 2. Its caller needs that whole product, not just the 1 it received.

Your original assignment asked to store factorial of 2 in answer, so it needs the result of that call. Now the frame for factorial of 2 leaves as its 2 takes the call’s place in the assignment. So answer holds 2, and no factorial call is left waiting. Each call gives its result only to its immediate caller, so each multiplication had to finish in turn before you could get your answer.