Unpredictable output [duplicate]
Possible Duplicate:
FAQ : Undefined Behavior and Sequence Points
#include<iostream>
#include<stdio.h>
int main(){
int myVal = 0;
printf("%d %d %d\n", ++myVal,myVal,++myVal);
myVal = 0 ; /*reset*/
std::cout<<++myVal<<" "<<myVal<<" "<<++myVal<<std::endl;
return 0;
}
I got the output 2 2 2 in both the cases. How could it be 2 2 2? I expected 2 开发者_运维问答1 1 or 1 1 2
The pre-incrementation operator is actually compiled so all calls to it are executed before the expressions calling printf and cout are evaluated.
It's just as if you had:
int myVal = 0;
myVal += 1;
myVal += 1;
printf("%d %d %d\n", myVal, myVal, myVal);
It could also imagined that compiler optimisations can go as far as using a constant '2' value instead of performing the incrementations at runtime in that case.
edit: diclaimer : this answer is an attempt at explaining what happened specifically in the case of the OP's code, but it really is an example of undefined behaviour, as compilers can do pretty much whatever they want in this situation.
精彩评论