-2

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?

Cipri
  • 69
  • 1
  • 8
  • 5
    @HolyBlackCat: `n` is used twice in the return expression, careful with order of evaluation guarantees... – Mat Jul 02 '18 at 08:38
  • 2
    please pick a language : C++ != C (especially if you get into the nooks and crannies like sequencing) – Sander De Dycker Jul 02 '18 at 08:47
  • 1
    @HolyBlackCat: There is a difference between n-1 and --n in this code. You will get incorrect result with --n. –  Jul 02 '18 at 08:47

2 Answers2

4

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).

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
3

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.

Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569
  • I would rather say "can be incorrect", there is also a chance that it will evaluate as the OP expects (with `--n` at least) – Ctx Jul 02 '18 at 08:44
  • It depends what value you pass to fact in case of --n. For 0, it will crash, for 1 it will be correct. And then it will be incorrect. –  Jul 02 '18 at 08:49
  • It doesn't have to crash, since a tail recursion could be optimized to an iteration – Ctx Jul 02 '18 at 08:50
  • 1
    @JamesBond And it would yield correct results if n is evaluated, then decremented and finally fed to funct, which would be perfectly possible afaics – Ctx Jul 02 '18 at 08:51
  • Comments are correct, but I think OP's question is at a more superficial understanding level. – Remus Rusanu Jul 02 '18 at 08:51
  • 1
    @RemusRusanu Maybe, but this Q/A is not only for the OP, but for all interested readers – Ctx Jul 02 '18 at 08:57