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 line
is 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?
std::cout << f() << g(); The order of evaluation of the two function calls is unspecified; the compiler can call g() then f() , or it can call f() then g() . Same thing in your code; the compiler can squirrel away the value of a.a[0] the call a.b() , or it can call a.b() then grab the value of a.a[0] .
The cout object is the only print method specifically created for C++. cout is an object of the ofstream type. C++ was designed around object-oriented programming and has completely different syntax compared to the functions deriving from C. Accordingly, cout is considered the standard way of printing strings in C++.
It is used to display the output to the standard output device i.e. monitor. It is associated with the standard C output stream stdout. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator(<<).
cout does not have a return value. cout is an object of type ostream .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With