I am currently learning C with the "Programming in C" by Stephen G. Kochan (3rd edition). In the chapter on recursive functions the factorial-function is presented. The part with recursion is result = n * factorial(n - 1);
where n
is the formal parameter of the number whose factorial is to be calculated and factorial
is the function. Out of curiosity I changed the function call to factorial(--n)
and while my Linter gives me a warning saying this operation on n may be undefined this compiles and runs as expected (I use gcc on Ubuntu). I cannot grasp what is happening here. In my understanding I should end up with a product of 0 (0 * 0 * 0 * ... * 1) with the last value being a one. But still this function returns the right values as with factorial(n - 1)
.
Here is the complete code of the function:
unsigned long int factorial(unsigned int n)
{
unsigned long int result;
if (n == 0)
result = 1;
else
result = n * factorial(--n);
return result;
}
To clarify: my question does not concern the undefined behaviour (why is this undefined behavior?), but how exactly this particular case is handled by the compiler. As this question was marked a duplicate, the answer to which does not apply here (although @badp answers my question in the duplicate but it is not the accepted answer there), I will answer it here.
Answer
@StoryTeller supplied an example, where this way of writing the function (n * factorial(--n)
could lead to a behavior that is different from the one expected.
@Pedram Azad gave an example of how one could find out how the compiler handles this by inspecting the assembly listing. The file containing this code can be generated by running gcc prog.c -S -o prog.s
where prog.c
is the file containing the c-code and prog.s
is the file containing assembly-code. The important part is the -S
option.