Order of Evaluation in std::cout Arguments
The order of evaluation of arguments passed to std::cout can be confusing, especially when one or more arguments is a function call that modifies the value of another argument.
Code Example
Consider the following C 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; }
Unexpected Output
When executed, this code produces the following output:
Value of test is : 1 Return value of function is : 1 Value of test : 0
This output may seem surprising, as one might expect the value of test to be 1 after the foo function is called.
Explanation
The order of evaluation of arguments in std::cout is not specified by the C standard, except for a few specific cases such as logical operators (&&, ||) and the ternary operator (? :).
In this example, the compiler is free to evaluate the arguments in any order it chooses. In this case, the foo function is evaluated first, modifying the value of test to 1.0. However, the value of test stored in the std::cout statement is still 0.0, because the std::cout statement is evaluated before the foo function is called.
Solution
To ensure the desired order of evaluation, the code should be rewritten as follows:
std::cout << "Value of test before function call: " << test << std::endl; foo(test); std::cout << "Value of test after function call: " << test << std::endl;
This ensures that test is evaluated before and after the foo function call, producing the expected output:
Value of test before function call: 0 Value of test after function call: 1
The above is the detailed content of How Does Argument Evaluation Order Affect `std::cout` Output in C ?. For more information, please follow other related articles on the PHP Chinese website!