Tess Snider wrote:
In C, I guess you
could return an arbitrary negative value, since the function should
never be returning a negative value on good input data.
Hi Tess,
This is called a "pinball API" since the result to someone
who doesn't recognise that the return value needs to be
tested is essentially random. Much better to make that
requirement explicit in the API.
bool factorial(unsigned int *n);
used like this
unsigned int n;
n = 20;
if (factorial(&n)) {
fprintf(stderr, "too big\n");
exit(EXIT_FAILURE);
}
...
yeah it's more typing, but it forces the API user to either
deal with the error or give the code maintainer the hint that
the error is is ignored:
n = 20;
(void)factorial(&n);
The predominance of pinball APIs in the C standard lead to
a lot of criticism of the standard C library, as the poor
design of the API is a major source of buffer overflows in
code.
Also note that you don't need to abandon recursion because of
the stack issue -- you simply need to ensure the stack is not
exhausted. Simplest way to do that is to do some modelling
and restrict the range of the input:
int recursion(int r) {
assert(r < 100);
...
recursion(simpler(r));
}
and of course in real life you use a wrapper function with
the test to prevent it being unnecessarily tested (assuming
r < 100 ---> simpler(r) < 100).
Cheers,
Glen
--
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html