问题
Input/Output stream operators associativity in theory:
LEFT TO RIGHT
(for example, according to this: Sait Mary's University website
Input/Output stream operators associativity on practice:
#include <iostream>
int func0() {
std::cout << "func0 executed" << std::endl;
return 0;
}
int func1() {
std::cout << "func1 executed" << std::endl;
return 1;
}
int func2() {
std::cout << "func2 executed" << std::endl;
return 2;
}
int main() {
std::cout << func0() << func1() << func2() << std::endl;
return 0;
}
Output (MSVCPP 2010, 2012):
func2 executed
func1 executed
func0 executed
012
Press any key to continue . . .
This sample demonstrates that functions are called in RIGHT TO LEFT order (despite of their values are printed as expected LEFT TO RIGHT).
The question: How this code sample correlates with Standard words about LEFT TO RIGHT execution? And why functions execution performed in RIGHT TO LEFT order?
回答1:
Associativity defines the order of the operator<< calls, which will happen in order this way: ((((std::cout << func0()) << func1()) << func2()) << std::endl);
. The order in which the arguments to operator<< are evaluated is implementation-defined however, iirc, which is what you're testing here.
回答2:
How this code sample correlates with Standard words about LEFT TO RIGHT execution?
The output from the print statement is 012, as required.
And why functions execution performed in RIGHT TO LEFT order?
Because that is completely up to the implementation. With a few exceptions, the standard says absolutely nothing about the order in which the arguments to an operator are computed. Those exceptions are the comma operator, the trinary operator a ? b : c
, and the boolean short circuit operators &&
and ||
. (These are not sequence points if the operators are overloaded). You should not depend on the order in which operands are computed. Associativity and the order in which the arguments are different concepts.
来源:https://stackoverflow.com/questions/11354871/c-input-and-output-stream-operators-associativity