开发者

Outcome of the C/C++ code [duplicate]

This question开发者_Go百科 already has answers here: Closed 11 years ago.

Possible Duplicate:

Undefined Behavior and Sequence Points

What is the outcome of the following code:

#include <stdio.h>
int main() {
  int a = 3;
  a= (a = 2) + (a = 3);
  printf("%d", a);
}

Why do I get 6 as the output on gcc? Why not 5?


You're both writing and reading variable a between sequence points, so the result is formally undefined behavior.

Looking at the assembly code generated by your particular compiler will make it clear why you get a particular result, but the standard makes no guarantees at all.


Because the order of operations in "a= (a = 2) + (a = 3);" is implementation-dependent. If it was "a= (a = 2) + (b = 3);" the answer would be 5. It is possible that a super-exact reading of the spec may require that the answer be 5 (if the result of an assignment is the RHS of the equation and not the LHS)... but even if it is, you should never even consider relying on anything approaching this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜