increment and decrement with cout in C++ [duplicate]

不想你离开。 提交于 2020-12-23 18:27:08

问题


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?


回答1:


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! :)




回答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;



回答3:


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.



来源:https://stackoverflow.com/questions/65202047/why-compiler-shows-unexpected-result-when-we-use-both-prefix-and-postfix-increme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!