As far as I understand, a tail recursive function calls itself at the very last step (like the return statement) however, the first instance of the function is not terminated until all the other instances are terminated as well, thus we get a stack overflow after a number of instances are reached. Given that the recursion is at the very last step, is there any way to terminate the previous instance during or right before the next instance? If the only purpose of an instance is to call the next one, there is no reason why it should reside in memory, right?
Share
Yes, some compilers will optimize tail recursion so that it doesn’t require extra stack space. For example, let’s look at this example C function:
This function is pretty easy; it just returns 1. Without optimizations, clang generated code on my machine that looks like this:
As you can see, the recursive call is in there at 0x24. Now, let’s try with higher optimization:
Now, look at that – no more recursion at all! This example is pretty simple, but the optimization can still occur on more complicated tail recursive cases.