Outcome of the C/C++ code [duplicate]
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.
精彩评论