Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 348
FailedDev Avatar asked Oct 10 '11 20:10

FailedDev


3 Answers

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.

like image 77
Matteo Italia Avatar answered Nov 05 '22 00:11

Matteo Italia


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.

like image 30
M.M Avatar answered Nov 05 '22 01:11

M.M


Order of evaluation is unspecified. It is not left-to-right, right-to-left, or anything else.

Don't do this.

like image 12
John Dibling Avatar answered Nov 05 '22 02:11

John Dibling