This is an old revision of the document!
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.
Fibonacci sequence
Let us consider the following recursive function that computes the n-th Fibonacci number (n = 0 is the first one):
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) + +->fibo(3) | + | +->fibo(2) | | + | | +->fibo(1) | | | | | +->fibo(0) | | | +->fibo(1) | +->fibo(2) + +->fibo(1) | +->fibo(0)