I'm new to C++ and study the increment and decrement operators. So I tried this example:
int x = 4;
cout << ++x << " " << x++ << " " << x++ << endl << endl;
cout << x << endl;
It returns this weird output on C++ .NET and QtCreator and 5 online C++ compilers:
7 5 4
7
The weird thing is that I expect something like this:
5 5 6
7
Can you explain what happens?
答案 0 :(得分:13)
Please notice that cout << x++ << ++x;
is just another notation for:
operator<<( operator<< (cout, x++), ++x);
The order in which your x++ and ++x statements are evaluated is undefined, so is the effect of your code.
Even if it seems to happens from right to left in your particular examples, you should not rely on that by any means.
Just make another experiment by using multiple statements as:
cout << ++x << " ";
cout << x++ << " ";
cout << x++ << endl;
The solution to your problem is:
Never write code which results in undefined behaviour! :)
答案 1 :(得分:2)
The result is undefined for your example. This is because the order of evaluation of x++
or ++x
in a line are undefined.
In short if you want predictable behaviour when using operator ++ then the variable it is applied to should only appear once in the expression being evaluated.
答案 2 :(得分:2)
This is what is called undefined beehive, and is dependent on what compiler you use, to better understand this you have to know computer architecture and how compiler works:
cout << x++ << hello << x++ << endl
one compiler can convert this sequence to binary sequence, that would do following
increment x
print x
print hello
increment x
print x
print endl
while second compiler can do it as following
print x
increment x
print hello
print x
increment x
print endl
third one can do it as following
print x
print hello
print x
print endl
increment x
and forth one can do following
increment x
print x
print hello
print x
print endl
your best bet to sort this issue is:
x++;
cout << x << hello;
x++;
cout << x << endl;