++(*it)
will increment and return the element it
refers to, not the iterator itself, so v[0]
is 2
after evaluating that expression.
So why doesn't it print 222
?
Because the chain of operator<<
s is actually nested function call, somewhat like this:
operator<<(operator<<(operator<<(operator<<(std::cout, ++(*it)), " "), v[0]), " ");
and the bit of interest:
operator<<(operator<<(std::cout, ++(*it)), " "), v[0])
This is a function call with two arguments, operator<<(std::cout, ++(*it))
and v[0]
.
The order in which function arguments are evaluated is unspecified, one platform or compiler may do it differently than another (left to right and right to left are common, as far as I know).
If the second argument is evaluated first, v[0]
is retrieved while still holding 1
, and we print 212
.
If the first argument is evaluated first, ++(*it)
happens first, and v[0]
is retrieved after, so we print 222
.
Unfortunately, the C++ standard only guarantees that the evaluation of all arguments is sequenced before the function body, but not with respect to each other.
Using both v[0]
and ++v[0]
in unsequenced expressions may invoke undefined behavior - which could do exactly what you want, or launch the missiles.