The order of writing a global variable from

In the program below, I call the function foo() , which sets the global variable i and then calls the constructor class A , where i must also be set, but up to 10 . However, the output of my program is 3 0 , can you explain?

 #include <iostream> int i; class A { public: ~A() { i=10; } }; int foo() { i = 3; A ob; return i; } int main() { std::cout << "i = " << foo() << " " << i << "\n"; } 
+4
source share
4 answers

There are two important points here:

The evaluation order of the arguments to the Unspecified function. So either:

  • foo() is executed first or
  • i is printed first

It is specific to your compiler. It looks like your compiler evaluates the argument from right to left, so global i , which 0 evaluates to 0 . Remember that this order may be different for other compilers, and you should not rely on the behavior of one implementation.

How about 3 ? The destructor for ob is called after the function returns. So i gets the value 10 after return, what is returned is a copy, and this copy has a value of 3 .

+5
source

This is because the return value is copied after the destructor. I print first, and foo is called later, so the output is 3 0.

If you print as below

 cout << "i = " << i <<" " << foo()<< endl; 

you will see 10 3 as an output.

+1
source

You are currently passing "i" as an argument, the value is zero. Foo () will change the value in the destructor to 10 after that.

As juanchopanza suggested, add another line std :: cout <i; and you will see what you expect, because at that moment the value is 10.

0
source

Print foo() and i with two cout statements as follows:

  cout << "i of foo = " << foo(); cout <<"\ni in main = " << i << endl; 

The output will be

  i of foo = 3 i in main = 10 

You used to get 3 0 output as output because the overloaded << operator was evaluated from left to right by your compiler.

0
source

Source: https://habr.com/ru/post/1486542/


All Articles