简体   繁体   中英

Can someone explain me why is that the output, C++ recursive function

I don't understand why after running this code

int n;
int f(int x) 
{ 
    int n; 
    if (x > 0) 
    {
        if (x % 2 == 0) 
        {
            cout << x % 10;
            n = 1 + f(x / 10); 
        } 
        else 
        {
            n = 1 + f(x / 10);
            cout << x % 10; 
        }
        return n; 
    } 
    else return 0;
}

int main()
{
    cout << ' ' << f(8174);
    return 0;
}

I get 4817 4 instead of 48174

I need more words but i dont know what to say:))

Before C++17 order of argument evaluation is unspecified. This means compiler can either run f(8174) (and therefore all of its std::cout <<... statements) before std::cout << ' ' or after that.

The fix is rather simple, you need to split your cout into two statements:

int main()
{
    std::cout << ' ';
    std::cout << f(8174)
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM