I almost understand how tail recursion works and the difference between it and a normal recursion. I only don\'t understand why it doesn\'t
Tail recursion can usually be transformed into a loop by the compiler, especially when accumulators are used.
// tail recursion
int fac_times (int n, int acc = 1) {
if (n == 0) return acc;
else return fac_times(n - 1, acc * n);
}
would compile to something like
// accumulator
int fac_times (int n) {
int acc = 1;
while (n > 0) {
acc *= n;
n -= 1;
}
return acc;
}
My answer is more of a guess, because recursion is something relating to internal implementation.
In tail recursion, the recursive function is called at the end of the same function. Probably compiler can optimize in below way:
As you can see, we are winding up the original function before the next iteration of the same function, so we are not actually "using" the stack.
But I believe if there are destructors to be called inside the function then this optimization may not apply.