开发者

Variable assignment and usage in the same expression

I encountered a line of code:

int a = 10;
int b = 40;
a = a + b - (b = a);
cout << a << "   " << b << endl;

I cannot understand wha开发者_如何转开发t happens in this code. Can anyone explain for me?


Undefined behavior. the value of b is changed and used for computation without an intervening sequence point. The results of the program are unpredictable - it can print anything or crash, or do do some nasty system calls.

Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.53) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.


Undefined behavior

http://en.wikipedia.org/wiki/Sequence_point


This is undefined behavior because vairable b has been modified then used in the same expression so the final result is ambiguous because it depends on the order of the expression evalution. The (b=a) could happen before or after b vairable being used to calcualte a+b.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜