Evaluation Order in std::cout
Confusion often arises regarding the order of argument evaluation when using std::cout's insertion operator. Consider the following code snippet:
#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; }
Surprisingly, the output of this code is:
Value of test is: 1 Return value of function is: 1 Value of test: 0
This violates the imagined left-to-right evaluation order.
Specific reason
In C, the order of evaluation of expression elements is undefined (except for some special cases, such as && and || operators and the introduction of ternary operator for sequential dots). Therefore, there is no guarantee that test will evaluate before or after foo(test) (which modifies the value of test).
Workaround
If the code relies on a specific order of evaluation, the easiest way is to split the expression in multiple separate statements, like this:
std::cout << "Value of test is: \t" << test << std::endl; foo(test); std::cout << "Return value of function is: " << foo(test) << std::endl; std::cout << "Value of test: " << test << std::endl;
This way the order of evaluation will be clearly defined from top to bottom.
The above is the detailed content of What Determines the Evaluation Order of Arguments in `std::cout`?. For more information, please follow other related articles on the PHP Chinese website!