Programming Fundamentals · Interview question

What is tail recursion, and why might it not matter in C?

A strong answer

A tail call is a recursive call whose result becomes the calling function's result with no further work, return helper(...); is a tail call, but return n * helper(...); is not, because the multiplication happens after the call returns. With a tail call, the compiler can reuse the current stack frame for the recursive call instead of pushing a new one, eliminating the stack-overflow risk entirely. This is called tail-call optimization (TCO). Some languages (Scheme, certain functional languages) require it; the C standard does not. C compilers will sometimes do it under -O2, but you can't rely on it for correctness. So in C, tail recursion is a nice-to-have rather than a guarantee, for depth-unbounded recursion, you should rewrite as a loop instead of trusting the optimizer.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Recursion

A function that calls itself. The base case, the recursive case, the call stack, and the question of when to use recursion vs a loop.

More Recursion questions

Browse all 472 interview questions
What is tail recursion, and why might it not matter in C? | EmbeddedPrep.io