The output you observed can be explained in this way: The expression is evaluated right-to-left *before* being passed to cout
or printf
for output.
Starting value is 1
i++ is post increment, ie it will print the value (1) and then
increment to 2: output 1
++i is pre-incremen, so 2 becomes 3 before it is printed: output 3
finally, the current value of i (3) is printed: output 3
These respective values are passed to the output routine.
To clarify, my answer only tries to explain the observed behavior, not lay down hard and fast rules for how the compiler or output routines order their evaluations/actions.
Having said that, this type of code is not good practice and quite likely to cause all sorts of problems that could be avoided.