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.

#include<stdio.h>

int factorial(int n) {
	if (n == 0)
		return 1;

	n = n * factorial(n - 1);

	return n;
}

int main() {
	printf("%d", factorial(5));
	return 0;
}

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

             factorial(5)
               /       \
             5    factorial(4)
            /             \
          4          factorial(3)
         /                   \
       3                factorial(2)
      /                         \
    2                    factorial(1)
   /                                 \
  1                             factorial(0)
                                       \
                                        1

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 ).

#include<stdio.h>

int fact_wrapper(int n, int m) {

	if (n == 0)
		return m;

	return fact_wrapper(n - 1, m * n);
}

int factorial(int n) {
	return fact_wrapper(5, 1);
}

int main() {
	printf("%d", factorial(5));
	return 0;
}

Let us see recursion tree of above program.

    factorial(5)
           |
    fact_wrapper(5,1)
           |
    fact_wrapper(4,5)
           |
    fact_wrapper(3,20)
           |
    fact_wrapper(2,60)
           |
    fact_wrapper(1,120)
           |
    fact_wrapper(0,120)
           |
          120

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:

https://www.quora.com/What-is-tail-recursion-Why-is-it-so-bad

https://en.wikipedia.org/wiki/Tail_call



Related Contents to follow