ESCM
ESCM

Reputation: 262

Why does the pre-decrement cause strange changes?

I have the following code in C++

int factorial_recursivo(int factorial) {

 if(factorial <= 1) return 1;

 // To show all the factors in each iteration std::cout << factorial << std::endl;

 return factorial * factorial_recursivo(--factorial);

}

However, if i write a number n, the result is the factorial of the number n-1.

If i change the last line of code the factorial_recursivo(--factorial) by factorial_recursivo(factorial - 1) works properly.

Why this happen? I even printed the factors in console and it correctly showed. Per example, with factoria_recursivo(5) i got 5 4 3 2, however the result was 24.

Upvotes: 4

Views: 92

Answers (2)

bhristov
bhristov

Reputation: 3197

You should do value - 1 instead:

return factorial * factorial_recursivo(factorial-1);

Executing:

return factorial * factorial_recursivo(--factorial);

results in unsequenced modification and access to factorial. On my laptop it actually produces 6 regardless of what I input as a parameter. Thank you M.M for asking me to clarify this in the comments. This is an example of undefined behavior.

Unsequencing occurs when the end result depends on which operand gets executed first. A simple example of this would be: arr[j] = arr2[++j]; The result of this would depend on whichever gets executed first, whether it would be arr[j] or arr2[++j]. .

Upvotes: 2

M.M
M.M

Reputation: 141628

The program has undefined behaviour because the operands of * are unsequenced, and so there are unsequenced read and writes of factorial.

The problem is essentially the same as the cases in this thread: Undefined behavior and sequence points

Upvotes: 2

Related Questions