Assuming you wanted the parameter --1
:
This causes a compile error:
fat2.c:10:27: error: lvalue required as decrement operand
return n * fatqua(--1) ;
Just to make it clear, lvalue
is the same as locator value . This means that the function expects to receive an addressable value, not a constant.
Assuming you wanted the parameter --n
:
Well, here's something interesting and your question has already been asked in stackoverflow. We have this link and in this other some useful answers.
Here are some important points:
- Using
--n
will cause the decrease before the statement is executed. Due to the pre-decrement, the evaluated expression will be (n-1) * fatqua(n-1)
;
- The multiplication is commutative (A * B = B * A), and this makes it dangerous to evaluate this expression. The order of evaluation of the arguments is undefined in this case. This is why it is a good practice not to use a variable that you are incrementing or decrementing twice in the same expression.
-
If you would like to use --n
to solve the factorial, run the following code:
#include <stdio.h>
unsigned int fatqua(unsigned int n){
printf("\nnumero : %d", n);
if (n < 2)
return 1;
return fatqua(--n) * (n+1);
}
void main() {
unsigned int n, resul = 0;
printf("Digite um numero: ");
scanf("%d", &n);
resul = fatqua(n);
printf("\n\n Fatorial de %d eh igual a: %d\n", n, resul);
}
Note that it looks horrible and very less readable than the first form (with (n-1)
in the recursive call parameter). Also, one detail would be to use unsigned int
also, since there is no factorial of negative number. I stress once again, for the above reasons, that you should use
return n * fatqua(n-1);