Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

c++ - Behavior of post increment in cout


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
cout << i++ << i--

is semantically equivalent to

operator<<(operator<<(cout, i++),   i--);
           <------arg1--------->, <-arg2->

$1.9/15- "When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function. [ Note: Value computations and side effects associated with different argument expressions are unsequenced. —end note ]

C++0x:

This means that the evaluation of the arguments arg1/arg2 are unsequenced (neither of them is sequenced before the other).

The same section in the draft Standard also states,

If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

Now there is a sequence point at the semicolon at the end of the full expression below

operator<<(operator<<(cout, i++), i--);
                                      ^ the interesting sequence point is right here

As is clear, evaluation of both arg1 and arg2 lead to side effect on the scalar variable 'i', and as we saw above, the side effects are unsequenced.

Therefore the code has undefined behavior. So what does that mean?

Here is how 'undefined behavior' is defined :) in the Standard.

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed.

Do you see correlation with @DarkDust's response 'The compiler is even allowed to set your computer on fire :-)'

So any output you get from such a code is really in the dreaded realm of undefined behavior.

Don't do it.

Only thing that is defined about such code is that it helps OP and many of us get lots of votes (if answered correctly) :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...