For example, I have a recursive function which calculate n!.
int fact(int n){
if(n==1)
return 1;
return n*fact(n-1);
}
My question is why I can't replace n-1 with n--? Or can I replace it with --n?
For example, I have a recursive function which calculate n!.
int fact(int n){
if(n==1)
return 1;
return n*fact(n-1);
}
My question is why I can't replace n-1 with n--? Or can I replace it with --n?
There are two reasons.
One, n--
is post-decrement. The value used as the arugment would be the original (non-decremented) value of n
.
Two, n
is used twice in the expression (once as the left-hand side argument of *
, and once within the argument to the recursive call). Neither C nor C++ specify evaluation order in this case, so it would be unclear whether the n
is evaluated before or after n--
(or even --n
).
because it changes the value of n
. Since the value is used to compute the expression n * fact(...)
, the value of n
must be read after the fact
is evaluated. Since --n
(or n--
, it does not matter here) must be passed as value to fact
, the decrement must occur before the fact
is invoked. Therefore the expression result will be incorrect.