1

I wrote a program that calculates factorial of given nuber by recursion and additionally displays the number of recursion calls.

It works as expected, when i store result in separated variable "result"

long long result = calculateFactorial(factorialNumber, counter);

    cout << "\nfactorial is equal to: " << result
         << "\nRecursion executed: " << counter - 1 << " times.\n";

but when i want to do it like that:

    cout << "\nfactorial is equal to: " << calculateFactorial(factorialNumber, counter)
         << "\nRecursion executed: " << counter - 1 << " times.\n";

the counter is always equal to initial value -1 (-1). Can you explain me, why the second way does not work properly?

Code:

#include <iostream>

using namespace std;

long long calculateFactorial(int factorialNumber, int &counter);

int main() {
    int counter = 0;
    int factorialNumber;

    cout << "Enter factorial number: ";
    cin >> factorialNumber;

    long long result = calculateFactorial(factorialNumber, counter);

    cout << "\nfactorial is equal to: " << result
         << "\nRecursion executed: " << counter - 1 << " times.\n";
    //counter - 1, because first execution is nor recursion.
}

long long calculateFactorial(int factorialNumber, int &counter) {

    if (factorialNumber == 0) {
        return 1;
    }

    if (factorialNumber > 0) {
        counter++;
        return factorialNumber * calculateFactorial(factorialNumber - 1, counter);
    }
    return 2;
    //error code - can be captured
}

Thanks :)

melpomene
  • 84,125
  • 8
  • 85
  • 148
Robert Lewandowski
  • 213
  • 1
  • 2
  • 8
  • 3
    Probably the compiler evaluated `counter - 1` before calling `calculateFactorial`. (Technical reading: http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – kennytm Mar 04 '17 at 14:55
  • 2
    This is a duplicate but I can't find a good question to redirect to. It boils down to http://stackoverflow.com/questions/2934904/order-of-evaluation-in-c-function-parameters but in a slightly non-obvious way. – melpomene Mar 04 '17 at 14:57
  • As the others said, `counter - 1` is evaluated before `calculateFactorial`. With [gdb](https://www.gnu.org/software/gdb/) : `15 << "\nRecursion executed: " << counter - 1 << " times.\n";` And *then* : `14 cout << "\nfactorial is equal to: " << calculateFactorial(factorialNumber, counter)` – adentinger Mar 04 '17 at 15:03

0 Answers0