Order of evaluation of arguments using std::cout

2018-12-31 18:59发布

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!

4条回答
看淡一切
2楼-- · 2018-12-31 19:45

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.

查看更多
泛滥B
3楼-- · 2018-12-31 19:48

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

Don't do this.

查看更多
人间绝色
4楼-- · 2018-12-31 19:49

The order of evaluation is unspecified, see http://en.wikipedia.org/wiki/Sequence_point

This is the same situation as the example with the operator+ example:

Consider two functions f() and g(). In C and C++, the + operator is not associated with a sequence point, and therefore in the expression f()+g() it is possible that either f() or g() will be executed first.

查看更多
冷夜・残月
5楼-- · 2018-12-31 19:57

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.

查看更多
登录 后发表回答