I think the weird behaviour you are wondering about is because of the order in which the redirected arguments are parsed and executed.
#include <iostream>
using namespace std;
int main()
{
int i = 1;
cout << i << i << i++ << i << i << i++ << endl;
return 0;
}
In this particular case, on the particular compiler I am using... (i.e. this is all undefined or unspecified behaviour - I am just trying to interpret the results. You should always avoid writing code which triggers undefined behavour).
Arguments 3 and 6 are evaluated first (Because they have the ++
operators attached? thanks rodrigo).
So the rightmost i++
evaluates to 1
and leaves i
as 2
.
Next the 3rd argument i++
is evaluated, giving 2
and leaving i
as 3
.
All other arguments evaluate to 3
. That is how you get the output
332331
.
Note that the order of evaluation for redirected elements is not specified, that is, it could change from compiler to compiler etc, you can't know what it will be.
See also
Order of evaluation of arguments using std::cout
As @rodrigo points out to me, since i
is incremented twice in the same expression the results are undefined.
So there are many gremlins at play, this is one possibly-correct, possibly-incorrect interpretation of how the output is generated.