Compilers
What is the effect of applying tail-call optimization to the final recursive call in the function above?
int fact(int n, int acc) {
if (n <= 1) return acc;
return fact(n - 1, acc * n);
}
- AThe number of recursions halves, and the result is computed twice as fast
- BThe function is inlined, and the recursion itself is replaced by a constant
- CThe call becomes a branch (jump), so the stack does not grow even with deep recursion
Show answer and explanation
Answer: C. The call becomes a branch (jump), so the stack does not grow even with deep recursion
The recursive call here is the function's last action, and its result is returned directly (a tail call). Since nothing remains after the call, the current stack frame can be reused by updating the arguments and jumping back to the function's start. This makes it behave like a loop, so the stack does not grow however deep the recursion, removing the risk of overflow. The number of steps is unchanged, and n is known only at run time, so it cannot become a constant.
- A. The number of steps is unchanged.
- B. n is known only at run time, so it cannot become a constant.
- C. Correct. The call becomes a jump, and the stack stops growing.