+ 2
Why does this happen?
#include <iostream> using namespace std; int main() { int x = 0; cout << ++x << ++x << ++x << endl; return 0; } /* Output 333 I think it should out 123 */ And #include <iostream> using namespace std; int main() { int x = 0; cout << ++x; cout << ++x; cout << ++x << endl; return 0; } /* Output 123 As it should be */ Another case with x++
4 Answers
+ 10
Because for the first case ++x increments x by one and immediatly stores its value in x 3 times, giving 333 as the answer. The expression is evaluated one at a time in the second case so you get 1 2 3.
+ 8
Moral of the story is that it's generally not advised to used multiple post/prefix increment/decrement operators in a single line. The behaviour of the program will differ from compiler to compiler. We have had a thread on this which sparked quite a discussion.
+ 5
Whenever there are more then one << operators in a cout statement the evaluation is done from right to left but outputed from left to right. This is because in cout << is an overloaded operator and so it behaves like a function call, that is in order to find the value of the part on the left of << you have to evaluate the code on its right.
According your code
cout << ++x << ++x << ++x << endl;
Will start evaluating value of x from right to left but print output from left to right. That is the last ++x is evaluated first so x becomes 1 followed by middle x++ so x noe is 2 and finally calculates the first x++ making the final x value 3. Now cout prints your x values as 333. Hope i was clear in explaining this. It is a bit confusing.
In your 2nd code you are using different cout statements so it results in singular evaluation of the increments and so you get 123
+ 2
Because "++" has higher precedence in comparison with "<<" .Therefore, initially the value of x increments 3 times and the result will be shown 3 times afterwards.
In the second block of code, that process occures separately in each line therefore results in 123.