Order of Argument Evaluation in std::cout
Understanding how function arguments are evaluated in C is crucial to avoid surprises in your code. In the context of std::cout, the evaluation order of arguments can be confusing, as illustrated in the following example:
#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; }
This code may appear to print the value of test before and after calling the foo function. However, the output suggests otherwise:
Value of test is : 1 Return value of function is : 1 Value of test : 0
This behavior is due to the unspecified order of evaluation in an expression. While it might seem intuitive for the argument farthest to the right (the value of test) to be evaluated first, this is not guaranteed.
To ensure the desired evaluation order, explicitly split the expression into separate statements, as shown below:
double value = test; std::cout << "Value of test is : \t" << value << "\tReturn value of function is : " << foo(test) << "\tValue of test : " << test << std::endl;
This ensures that the value of test is copied into value before the foo function is called. As a result, the output now accurately reflects the expected order of evaluation:
Value of test is : 0 Return value of function is : 1 Value of test : 1
The above is the detailed content of How Does C 's `std::cout` Evaluate Arguments, and Why Does Order Matter?. For more information, please follow other related articles on the PHP Chinese website!