Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using --a vs a-1 in recursion [duplicate]

Tags:

c++

I was trying to calculate a factorial using recursion like this:

#include <iostream>

using namespace std;

int factorial(int a)
{
    if(a == 0)
    {
        return 1;
    }
    return a*factorial(--a);
}

int main()
{
    int a;
    cin >> a;

    cout << factorial(a) << endl;

    return 0;
} 

and it wasn't working. Then, I made a small change:

#include <iostream>

using namespace std;

int factorial(int a)
{
    if(a == 0)
    {
        return 1;
    }
    return a*factorial(a-1);
}

int main()
{
    int a;
    cin >> a;

    cout << factorial(a) << endl;

    return 0;
} 

... and it started working!

The problem is that I don't see any difference between these codes: Why didn't it work in the first code?

like image 964
NiceProgrammer Avatar asked Aug 06 '26 11:08

NiceProgrammer


1 Answers

In your first code sample, the following line has undefined behaviour:

return a * factorial(--a);

This is because there is nothing in the C++ Standard that dictates whether or not the 'old' or 'new' (decremented) value of a is used to multiply the return value of the factorial function.

Compiling with clang-cl gives the following:

warning : unsequenced modification and access to 'a' [-Wunsequenced]

In your second code sample, there is no such ambiguity, as a is not modified.

like image 162
Adrian Mole Avatar answered Aug 08 '26 02:08

Adrian Mole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!