Help? Why such a conclusion?

#include <iostream>
using namespace std;

int a = 8;

int g()
{
    a++; 
    return a - 1;
}

int f()
{
    a++;
    return a;
}

int main()
{
    cout << g() << " " << f() << " " << g() + f() << endl;
    system("PAUSE");
    return 0;
}

Exit "11 11 18"

+3
source share
6 answers

Function evaluation order is not defined in C ++. In code:

cout << g() << " " << f() << " " << g() + f() << endl;

The compiler can emit code to call f (), f (), g (), g (), and then add the results. Or it can do something else.

This has nothing to do with using cout, BTW - if you write code like this:

x = a() + b() * c();

There is no guarantee what calls will cause a, b and c. This is one of the many reasons global variables are A Bad Thing - you often cannot predict how functions that change them will be called.

+9
source

. g() + f(), 8 + 10 = 18. a == 10 f(), 11 a 11 ..

+4

g() + f(), , a 10, 18. , g() f() . g() 8+10, 9+9.

f(), a 11 11.

g(), a 12 11.

, cout .

" " . , , ( , , ), , .

, , . , (, , ) , , , : -)

+4

The execution order is not guaranteed if the sequence of points is not specified in the expression . If you want to know the order here, you need to break it down into separate statements.

cout << g() << " ";
cout << f() << " ";
int temp = g();
temp += f();
cout << temp << endl;
+3
source

a is a global variable, and everyone accesses it. In addition, the operator <turns from right to left, therefore: g () + f () = 8 + 10 = 18 (and after 10) f () = 11 and a is 11
g () = 11 and a is 12

+2
source
cout << g() << " " << f() << " " << g() + f() << endl;

same as

cout.operator<<(operator<<(operator<<(operator<<(operator<<(operator<<(endl), g() + f()), " "), f()), " "), g());

The order called by the functions is the reason for this.

0
source

All Articles