caramel1995
caramel1995

Reputation: 3055

Called a function with "cout" statement inside a "cout" statement

I came across this rather vague behavior when messing around with code , here's the example :

#include <iostream>

using namespace std;


int print(void);

int main(void)
{
    cout << "The Lucky " << print() << endl;     //This line
    return 0;
}

int print(void)
{
    cout << "No : ";
    return 3;
}

In my code, the statement with comment //This lineis supposed to print out The Lucky No : 3, but instead it was printed No : The Lucky 3. What causes this behavior? Does this have to do with C++ standard or its behavior vary from one compiler to another?

Upvotes: 19

Views: 15600

Answers (3)

Azhar Sindhi
Azhar Sindhi

Reputation: 37

In my compiler No: The Lucky 3 is the output.... it means that its behaviour varies from compiler to compiler.

Upvotes: 0

Adam Trhon
Adam Trhon

Reputation: 2935

Let's call the operator << simply operator .

Now we can write

cout << "The Lucky"

as

operator(cout, "The Lucky")

The result of this operation is cout, and it is passed to next <<, so we can write

operator(operator(cout, "The Lucky"), print() )

It is a function invocation with two parameters, and the standard doesn't say anything about the order of their evaluation.

So with some compilers you really may get

The Lucky No : 3

Upvotes: 4

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

The order of evaluation of arguments to a function is unspecified. Your line looks like this to the compiler:

operator<<(operator<<(operator<<(cout, "The Lucky "), print()), endl);

The primary call in the statement is the one with endl as an argument. It is unspecified whether the second argument, endl, is evaluated first or the larger sub-expression:

operator<<(operator<<(cout, "The Lucky "), print())

And breaking that one down, it is unspecified whether the function print() is called first, or the sub-expression:

operator<<(cout, "The Lucky ")

So, to answer your question:

What causes this behavior? Does this has to do with C++ standard or its behavior vary from one compiler to another?

It could vary from compiler to compiler.

Upvotes: 18

Related Questions