Tail-end Recursion

Tail-end Recursion is an efficient way of writing recursive functions so that they use less memory on the stack and sometimes improve the complexity by recurring fewer times. However, in order to use the advantages of tail-end recursion compilers have to be optimized specifically to identify situations where the stack could be used more efficiently. The utility of Tail-end Recursion will be highlighted using a practical example involving a recursive procedure that computes the n-th Fibonacci number.

Let us consider the following recursive function that computes the n-th Fibonacci number:

int fibo (int n) {
  if (n < 2) {
    return n;
  }
  return fibo(n-1) + fibo(n-2);
}

The code works well and behaves as expected, but let us discuss the above function in terms of efficiency. The function calls are shown below:

fibo(4)                 //ninth evaluation, fibo(4) = fibo(3) + fibo(2) = 2 + 1 = 3
|
+->fibo(3)              //fifth evaluation, fibo(3) = fibo(2) + fibo(1) = 1 + 1 = 2
|  |
|  +->fibo(2)           //third evaluation, fibo(2) = fibo(1) + fibo(0) = 1 + 0 = 1
|  |  |
|  |  +->fibo(1)        //first evaluation, fibo(1) = 1
|  |  |
|  |  +->fibo(0)        //second evaluation, fibo(0) = 0
|  |
|  +->fibo(1)           //fourth evaluation, fibo(1) = 1
|
+->fibo(2)              //eighth evaluation, fibo(2) = fibo(1) + fibo(0) = 1 + 0 = 1
   |
   +->fibo(1)           //sixth evaluation, fibo(1) = 1
   |
   +->fibo(0)           //seventh evaluation, fibo(0) = 0

<stack diagram to be inserted here> <work in progress>