Undefined Output of cout << a << a
In the code snippet:
int a = 0; cout << a++ << a;
it is commonly assumed that the behavior is equivalent to:
cout << (a++) << a;
However, due to the lack of sequence points between function argument evaluations, the order of execution is not guaranteed. The compiler may evaluate a before or after std::operator<<<>(std::cout, a ).
Therefore, the correct interpretation is:
cout << ((a++) << a);
This means that the result is undefined, as the value of a after the increment is used in the second call to operator<<<>.
C 17 Amendment
In C 17, the rules have been modified such that:
E1 << E2
is evaluated as:
std::operator<<<>(std::operator<<<>(E1, E2), E3)
with all side effects of E1 sequenced before those of E2. This ensures that the code fragment now produces the expected output of "01".
The above is the detailed content of Why is the Output of `cout. For more information, please follow other related articles on the PHP Chinese website!