Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
For the code below:
main() {
int i = 1 ;
cout << i << ++i << i++ ;
}
Why do I get the output as 331 instead of what was expected i.e 122 ?
( Same is the case even if I use printf instead of cout ?)
<<is a function, namely something likeostream& operator<<(ostream& lhs, RhsType rhs).is equivalent to
The function returns lhs, that is
return lhs, – so in the above examplescoutis returned.So your example
is equivalent to
Correction C++ does not specify which order the increment operations are performed. It seems logical to you and me that the most nested would go first, but as far as the compiler is concerned it is free to execute the increment whenever it likes. It is the same behaviour as a function like
myFunc(cout, i++, ++i, i)where the order in which the increments are evaluated is undefined. The only thing guaranteed is the functions are evaluated inside to outside.