When doing tail recursive functions (especially tail recursive functions) it is often helpful to have a helper function in addition to another function which has a more friendly interface. The friendly interface function really just sets up the less friendly function's 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 passing an accumulator value you avoid having to use pointers or do any computations upon returning from called functions, which makes the functions truely tail recursive.
answer
instead of returning any value. And it seems to assume that*answer
is initialized to 1. – casablanca Oct 14 '10 at 16:52int
and does not actually return a value. – James McNellis Oct 14 '10 at 16:55void
would have worked just fine. – casablanca Oct 14 '10 at 16:55