froycard
froycard

Reputation: 435

Recursion Factorial in c++ Program using prefix decrements

why this recursion code fails? it fails, because it doesn't calculate factorial correctly (this is just the recursive function, you know), i.e. if I run "factorial(3)", it yields "2" instead of "6" (factorial (3) is 6, not 2). So it has a bug, doesn't it?

int factorial(int n){
    if(n>1) return n*factorial(--n);
    else return 1;    
}

if I use n-1 instead of --n, it fixes the bug? -->Moreover, if I use n--, I create a infinite loop I don't really get it

Upvotes: 0

Views: 101

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

Modifying (--n) and elsewhere using the value of a variable (n*) in the same expression, is Undefined Behavior.

Upvotes: 2

Related Questions