Possible Duplicate:
Undefined Behavior and Sequence Points
I’m not sure if this is a gcc bug or not, so I’ll ask:
unsigned int n = 0;
std::cout << n++ << n << ++n;
gcc gives the extremely strange result:
“122” which AFAICT is impossible. Because << is left associative, it should be the same as:
operator<<(operator<<(operator<<(std::cout, n++), n), ++n)
and because there is a sequence point before and after evaluating arguments, n is never modified twice (or even accessed) between two sequence points — so it shouldn’t be undefined behaviour, just the order of evaluation unspecified.
So AFAICT valid results would be:
111
012
002
101
and nothing else
There is a sequence point between evaluating arguments and calling a function. There is no sequence point between evaluating different arguments.
Let’s look at the outermost function call:
The arguments are
operator<<(operator<<(std::cout, n++), n)and
++nIt is unspecified which of these is evaluated first. It’s also allowed that the first argument is partially evaluated when the second argument is evaluated.
From the standard, section
[intro.execution](wording from draft 3225):Because you have multiple operations with side effects on the same scalar object which are unsequenced with respect to each other, you’re in that realm of undefined behavior, and even
999would be a permissible output.