Order of evaluation of arguments using std::cout
Hi all I stumbled upon this piece of code today and I am confused as to what exactly happens and more particular in what order :
Code :
#include <iostream>
bool foo(double & m)
{
m = 1.0;
return true;
}
int main()
{
double test = 0.0;
std::cout << "Value of test is : \t" << test << "\tReturn value of function is : " << foo(test) << "\tValue of test : " << test << std::endl;
return 0;
}
The output is :
Value of test is : 1 Return value of function is : 1 Value of test : 0
Seeing this I would assume that somehow the right most argument is printed before the call to the function. So this is right to left evaluation?? During debugging though it seems that the function is called prior to the output which is what I would expect. I am using Win7 and MSVS 2010. Any help is appreciated!
The evaluation order of elements in an expression is unspecified (except some very particular cases, such as the &&
and ||
operators and the ternary operator, which introduce sequence points); so, it's not guaranteed that test
will be evaluated before or after foo(test)
(which modifies it).
If your code relies on a particular order of evaluation the simplest method to obtain it is to split your expression in several separated statements.
The answer to this question changed in C++17.
Evaluation of overloaded operators are now sequenced in the same way as for built-in operators (C++17 [over.match.oper]/2).
Furthermore, the <<
, >>
and subscripting operators now have the left operand sequenced before the right, and the postfix-expression of a function call is sequenced before evaluation of the arguments.
(The other binary operators retain their previous sequencing, e.g. +
is still unsequenced).
So the code in the question must now output Value of test is : 0 Return value of function is : 1 Value of test : 1
. But the advice "Don't do this" is still reasonable, given that it will take some time for everybody to update to C++17.