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.
- Minimum difference between any two weighted nodes in Sum Tree of the given Tree
- K-th lexicographical string of given length
- Total number Of valid Home delivery arrangements
- Find a Mother vertex in a Graph using Bit Masking
- Queries for count of even digit sum elements in given range using MO's Algorithm
- Real time optimized KMP Algorithm for Pattern Searching
- Query to count odd and even parity elements in subarray after XOR with K
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
- Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1
- Range Queries for count of Armstrong numbers in subarray using MO's algorithm