We have discussed (in tail recursion) that a recursive function is tail recursive if recursive call is the last thing executed by the function.
We also discussed that a tail recursive is better than non-tail recursive as tail-recursion can be optimized by modern compilers. Modern compiler basically do tail call elimination to optimize the tail recursive code.
If we take a closer look at above function, we can remove the last call with goto. Below are examples of tail call elimination.
The above function can be replaced by following after tail call elimination.
Therefore job for compilers is to identify tail recursion, add a label at the beginning and update parameter(s) at the end followed by adding last goto statement.
This article is contributed by Dheeraj Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- QuickSort Tail Call Optimization (Reducing worst case space to Log n )
- Tail Recursion
- Tail Recursion for Fibonacci
- Tail recursion to calculate sum of array elements.
- Cyclic Iterator for K variable length vectors
- Maximum sum subarray after altering the array
- Reverse a singly Linked List in groups of given size | Set 3
- Restore a permutation from the given helper array
- Longest Increasing Subsequence using BIT
- Minimum cost to reverse edges such that there is path between every pair of nodes
- Sum of all the prime numbers with the maximum position of set bit ≤ D
- Count of quadruplets with given sum | Set 3
- Find distance of nodes from root in a tree for multiple queries
- Find parent of each node in a tree for multiple queries