Simply said, tail recursion is a recursion where the compiler could replace the recursive call with a "goto" command, so the compiled version will not have to increase the stack depth.
Sometimes designing a tail-recursive function requires you need to create a helper function with additional parameters.
For example, this is not a tail-recursive function:
int factorial(int x) {
if (x > 0) {
return x * factorial(x - 1);
}
return 1;
}
But this is a tail-recursive function:
int factorial(int x) {
return tailfactorial(x, 1);
}
int tailfactorial(int x, int multiplier) {
if (x > 0) {
return tailfactorial(x - 1, x * multiplier);
}
return multiplier;
}
because the compiler could rewrite the recursive function to a non-recursive one, using something like this (a pseudocode):
int tailfactorial(int x, int multiplier) {
start:
if (x > 0) {
multiplier = x * multiplier;
x--;
goto start;
}
return multiplier;
}
The rule for the compiler is very simple: When you find "return thisfunction(newparameters);", replace it with "parameters = newparameters; goto start;". But this can be done only if the value returned by the recursive call is returned directly.
If all recursive calls in a function can be replaced like this, then it is a tail-recursive function.
Tell us more about the context where you have encountered the term tail recursion. Link? Citation? – A.Schulz – 2012-10-22T09:05:37.583
@A.Schulz I have put the link to the context . – Geek – 2012-10-22T09:18:35.823
5
Look at "What is tail-recursion?" on stackoverflow
– Vor – 2012-10-22T09:24:43.443Why do you repeat questions? (http://stackoverflow.com/questions/11864006/why-is-quick-sort-called-a-tail-recursive-algorithm)
– ajmartin – 2013-01-05T00:24:04.1532@ajmartin The question is borderline on [so] but firmly on-topic on [cs.se], so in principle [cs.se] should produce better answers. It hasn't happened here, but it's still ok to re-ask here in the hope of a better answer. Geek, you should have mentioned your earlier question on SO though, so that people don't repeat what's already been said. – Gilles 'SO- stop being evil' – 2013-01-05T15:59:04.877
1Also you should say what is ambiguous part or why you are not satisfied by previous answers, I think on SO people provide good answers but what caused you to ask it again? – None – 2013-01-07T10:14:28.280
here is a nice video explaining this https://www.coursera.org/learn/progfun1/lecture/51t1e/lecture-1-7-tail-recursion
– Adelin – 2019-09-17T11:31:29.373