4

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";
}
Deepu
  • 7,592
  • 4
  • 25
  • 47
Rohit
  • 6,941
  • 17
  • 58
  • 102

4 Answers4

5

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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • The second point (about the destructor) I understood. Can you brief about the order of evaluation of arguments? –  Jun 17 '13 at 06:41
  • @NishithJainMR: Perhaps [**this**](http://stackoverflow.com/a/10782963/452307) old answer of mine will help you understand. – Alok Save Jun 17 '13 at 06:46
1

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.

shivakumar
  • 3,297
  • 19
  • 28
0

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.

user1764961
  • 673
  • 7
  • 21
0

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.

Deepu
  • 7,592
  • 4
  • 25
  • 47