开发者

Explanation of call ordering in a cout statement, postfix vs prefix

I was overloading the postfix and prefix ++ operator and testing them out, when I noticed something unexpected in the actual value output when printing out my test. As an example, here is an integer test:

int i = 0;
cout << "before prefix: " << i << " prefixing.. " << ++i << " after prefix. " << i << endl;

In my mind, this should print out "before prefix: 0 prefixing... 1 after prefix. 1"

To my dismay, this prints before prefix: 1 prefixing.. 1 after prefix. 1 Why is it already 1 at the start of the call?! Ok, maybe it parses through the statement before printing and i gets incremented before the printing even begins.

But then I tested the postfix integer incrementing...

int i = 0;
c开发者_运维百科out << "before postfix: " << i << " postfixing.. " << i++ << " after postfix. " << i << endl;

before postfix: 1 postfixing.. 0 after postfix. 1

The increment happens everywhere but the middle statement?! This is quite counter intuitive. Can somebody please shed some light on this?


Reading and incrementing a variable in the same statement (or, technically, between two sequence points, in this case, the semicolons) causes undefined behaviour - in other words, the compiler is allowed to do whatever it wants.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜