开发者

Confused about how unary operations result in this output [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

Multiple increment operators in single statement

Undefined Behavior and Sequence Points

can someone explain to me why this line of code generate such output? code (after initilizeing both i&j to zero):

cout<<i++<<','<<++j<<','<<--i<<','<<j--<<'\n';

output:

-1,0,0,0;

I know i++ means evaluate first then increase by 开发者_开发问答1, while ++i means increase by 1 then evaluate. but not sure what behavior is the multiple evaluation in a sequenced cout statement.

thanks!


The behavior of that code is undefined. An implementation is allowed to evaluate i++ before --i, or after it, or to stagger the evaluations such that the end results seem to make no sense at all.

It's even legal for an optimizer, when faced with code such as

if( k != 0 ) {
   cout << i++ << --i;
}
foofum(k);

to reason that because the code in the then branch is undefined behavior, then we can conclude that k is always zero, and reduce the entire thing to

foofum(0);

(This would be formally justified by the fact that the "undefined" behavior of the unsequenced updates to i just might happen to be assigning 0 to k and jumping to the closing brace. Undefined really does mean anything can happen).

Just don't write code like that.

Edit: It was suggested in a now-deleted answer that the effect of the statement is merely unspecified because the overloaded <<'s are function calls rather than native operators. However, that just makes the statement equivalent, for our present purposes, to

f(g(i++), i--);

(here the f represents a one-argument ostream::operator<<(), but the rules for evaluation order for AAA.f(BBB) and f(AAA,BBB) are the same). The compiler can decide in which order it evaluates the arguments to f. If it happens to evaluate i-- first, the evaluation order becomes:

  • i--
  • i++
  • sequence point
  • call g
  • sequence point
  • call f

Since there is no sequence point separating i-- and i++, undefined behavior results.

On the other hand, f(g(i+=h()), i++) is arguably merely unspecified under the sequence-point formalism. I think it reverts to undefined in C++1x's relational formulation.


The order of evaluation of arguments to a function in C/C++ is Unspecified.
The order in which arguments are being passed to << is Unspecified here and hence the result.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜