开发者

Unpredictable output [duplicate]

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

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜