Tuesday, 6 August 2013

Why we can't use static variables to achieve tail recursion?

Why we can't use static variables to achieve tail recursion?

I am learning C, so I am writting some little exercises in C to practice
the language.
I have experience with functional code, so I love recursion. I think that
it would be great to achieve tail recursion using C static variables, so
additional arguments or helper functions would not be required.
This code to calculate a factorial using recursion, fails:
long long int fact(int n)
{
static long long int result = -1;
if(n <= 0) {
if(result < 0)
return 1;
else {
long long int temp = result;
result = -1;
return temp;
}
} else {
result *= n;
fact(n - 1);
}
}
However, for some reason, I cannot do this in C. Is there an idiom to the
same that? Is it just my compiler? What about memoization?
Thanks a lot.

No comments:

Post a Comment