What is Tail Call Optimization and Tail Recursion? what is difference between normal recursion and tail recursion? Tail recursion is a  recursion where the recursive call is the very last thing in the function. what is meaning of the very last thing? Let us write a normal recursive function of a factorial.

To calculate factorial of 5 , the recursive function factorial(int n)  call itself and produces following recursion tree.

So  from the recursion tree we can conclude that each call to function factorial would create an extra variable (5,4,3,2,1) on the stack. However we can optimize our recursion to avoid creation of extra variables on stack. Let write an optimize version of factorial function ( tail recursion ).

Let us see recursion tree of above program.

From the above recursion tree it is clear that no extra variables are created on stack. Also look at the function fact_wrapper , the function fact_wrapper calls itself from the very end of the function. This type of recursion is tail recursion.

## Tail Call Optimization and Tail Recursion

Tail call optimization is also know as tail call elimination or tail call merging. It is generic term used for tail recursion. Tail recursion avoid new stack frame. Avoiding new stack frame reduces the memory complexity.

Ref: