Tail recursion in C
2 answers
When doing tail-recursive functions (especially tail-recursive functions), it is often useful to have a helper function in addition to another function that has a friendlier interface. A friendly interface function does set less friendly function arguments.
static unsigned factorial_helper(unsigned input, unsigned acc) {
if (intput == 0) {
return acc;
}
return factorial_helper(input-1, acc * input);
}
unsigned factorial(int input) {
if (input < 0) {
do_something_bad();
}
return factorial_helper(input, 1);
}
By skipping the accumulator value, you avoid using pointers or any computation when returning from called functions, which makes the functions truly tail-recursive.
+6
source to share
Here's a link with the definition: http://phoenix.goucher.edu/~kelliher/cs23/feb21.html
"A function is recursive with a tail if the last thing it does is call it recursively."
In the code you posted, the last thing the function does is make a recursive call to itself, so by this definition it is tail-recursive.
+4
source to share