Argument Evaluation Order in std::cout
In C , the order of argument evaluation in stream insertion operator (std::cout) is unspecified. This can lead to unexpected behavior when multiple arguments are inserted simultaneously.
Consider the following 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 expected output of this code is:
Value of test is : 1 Return value of function is : 1 Value of test : 1
However, the actual output may vary depending on the compiler and platform. The code may print:
Value of test is : 1 Return value of function is : 1 Value of test : 0
This is because the evaluation order of the arguments in the std::cout statement is not defined. In the first case, test is evaluated before the foo() call, so it prints 1. In the second case, test is evaluated after the foo() call, so it prints 0.
To ensure proper ordering, split the expression into multiple statements:
double test_after_foo = foo(test); std::cout << "Value of test is : \t" << test << "\tReturn value of function is : " << test_after_foo << "\tValue of test : " << test_after_foo << std::endl;
This guarantees that foo(test) is evaluated before the std::cout statement, providing consistent output across different compilers and platforms.
The above is the detailed content of Why is the Order of Argument Evaluation in `std::cout` Unspecified, and How Can I Ensure Consistent Output?. For more information, please follow other related articles on the PHP Chinese website!