mercredi 22 juillet 2015

Can someone explain this C++ program.The result is weird :(

This is a problem in a test. I expect the result is 1:1 but run it and get the answer 1:5, although I've debug it in Visual C++ 2013 and see the value of the adress which 'a' point to is 1 (the last '1' in 1:1)

#include <iostream>
using namespace std;
int fact(int *a)
{
    if (*a <= 1)
    {
        return a[0];
    }
    else
    {
        return a[0] * fact(&(--*a));
    }
}
int main()
{
    int *a = new int;
    *a = 5;
    cout << fact(a) << ":" << *a;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire