unexpected output in cout and printf [duplicate]

只愿长相守 提交于 2019-11-29 18:05:24

<< is a function, namely something like ostream& operator<<(ostream& lhs, RhsType rhs).

cout << a;

is equivalent to

operator<<(cout, a);

The function returns lhs, that is return lhs, - so in the above examples cout is returned.

So your example

cout << i << ++i << i++ ;

is equivalent to

operator<<(operator<<(operator<<(cout, i), ++i), i++);

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.

The compiler is free to change the order of evaluation. You are changing i multiple times on the same statament which causes undefined behaviour.

This is the reason why you should not write such code. I'm sure this will give you different results with different compilers. Using Visual C++ this gives you different output when run in Debug and Release versions.

The output you observed can be explained in this way: The expression is evaluated right-to-left *before* being passed to cout or printf for output.

Starting value is 1

i++ is post increment, ie it will print the value (1) and then increment to 2: output 1

++i is pre-incremen, so 2 becomes 3 before it is printed: output 3

finally, the current value of i (3) is printed: output 3

These respective values are passed to the output routine.

To clarify, my answer only tries to explain the observed behavior, not lay down hard and fast rules for how the compiler or output routines order their evaluations/actions.

Having said that, this type of code is not good practice and quite likely to cause all sorts of problems that could be avoided.

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