kayle
kayle

Reputation: 1156

C++ How cout is excuted in this program?

How the tryout.main() cout is executed first and then prints main() function cout and finally printing the return value of tryout.main(). This is bit confusing. can any one explain it?

#include<iostream>
using namespace std;
class TryOut
{
public:
 int main()
 {
    std::cout<<"In TryOut Main Function "<<std::endl;
    return 0;
 }
};

int main(int argc, char **argv)
{
TryOut tryout;
std::cout<<"In Main function: "<<tryout.main()<<std::endl;
return 0;
}

Output:

In TryOut Main Function 
In Main function: 0

Upvotes: 0

Views: 659

Answers (3)

Dariusz
Dariusz

Reputation: 22271

This is an edited answer. I was proven wrong by Igor Tandetnik, and since my answer was (incorrectly) accepted and highest voted, I decided to rewrite it to make it correct.

In our case

foo() = ostream& ostream::operator<<(const char*)

The order of execution in a sequence of:

obj.foo("str").foo(fun())

may be either:

obj.foo("str");
fun();
obj.foo(fun_res);

or

fun();
obj.foo("str");
obj.foo(fun_res);

In your case the latter happened, but the former is also a valid execution order.

The order guarantees are as follows:

  • fun() will happen before obj.foo(fun_res), because the result of foo is required for that call,
  • obj.foo("str") will happen before obj.foo(fun_res).

Hence the abovementioned two cases are possible.

Upvotes: 4

kfsone
kfsone

Reputation: 24269

"<<" in C++ is actually syntactic sugar, when you do

cout << "Hello"

you're actually calling either

ostream& operator<<(ostream&, const char*)

or

ostream& ostream::operator<<(const char*)

For convenience, I'm going to assume the latter. When you write

std::cout<<"In Main function: "<<tryout.main()<<std::endl;

this would compile to

cout.operator<<("In Main function: ").operator<<(tryout.main()).operator<<(std::endl);

So the code you wrote as

<<tryout.main()<<

says: "call tryout.main(), capture the return value, and pass that to "ostream::operator<<(int)", using the ostream returned by the previous <<.

So - now tryout.main() is called and executed, which does it's own output, quite independently, and then returns 0.

Now your main function is able to finish it's call chain with the return value of 0 as an argument.

Was there a reason you were not able to step through this with a debugger?

Upvotes: 0

Igor Tandetnik
Igor Tandetnik

Reputation: 52621

The order of evaluation of subexpressions within an expression is, in general, unspecified. tryout.main() may be legally called before or after std::cout<<"In Main function: " is executed. In your case, it happens to be called before.

Upvotes: 2

Related Questions