Rohit
Rohit

Reputation: 7161

Order of writing to a global variable from

In the program below I call a function foo() which sets a global variable i and then calls the constructor of class A, where i should also be set, but to 10. However the output of my program is 3 0, can you please 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";
}

Upvotes: 4

Views: 77

Answers (4)

Deepu
Deepu

Reputation: 7610

Print the foo() and i by using 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

Earlier you were getting 3 0 as output because the overloaded operator << was being evaluated from left to right by your compiler.

Upvotes: 0

user1764961
user1764961

Reputation: 693

At the moment you are passing the 'i' as the argument, it's value is zero. The 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 point the value is 10.

Upvotes: 0

shivakumar
shivakumar

Reputation: 3397

Its because return value gets copied after destructor. I gets printed first and foo gets called later so the output 3 0.

If you print like below

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

you will see 10 3 as output.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206518

There are two important points to consider here:

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

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

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

As for why 3? The destructor for ob gets called after the function returns. So i gets set to 10 after the return, what gets returned is a copy and that copy has a value 3.

Upvotes: 5

Related Questions