开发者

Why does this C program give unexpected output? [duplicate]

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

Possible Duplicate:

C programming: is this undefined behavior?

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

my expected output is 556. But when i executed it the result is 767. how?


You can't be sure that the increments are executed in the order you expect, because instructions inside arguments are executed in an order chosen by your compiler.


You are accessing and changing a value within a sequence point (changing it twice, infact), Within a sequence point you can't be sure about the order of operations.

i.e. while you read the function call from left to right, it isn't guaranteed that the expressions are evaluated in that order. The first i might be evaluated first, yielding 5. The i++ might be evaluated first, incrementing to 6 before both ++i and i are evaluated, and so on.


Interestingly Enough, the problem is that you are using the same variable more than once. If you change the code to this:

int i, j, k;
i=j=k=5;
printf("%i%i%i",i,j++,++k);

It works as expected. I think, that when you use the same variable, the order of operations gets messed up.


$ gcc -Wall arst.c  
arst.c:2:1: warning: return type defaults to ‘int’

arst.c: In function ‘main’:

arst.c:5:27: warning: operation on ‘i’ may be undefined

arst.c:5:27: warning: operation on ‘i’ may be undefined

arst.c:6:1: warning: control reaches end of non-void function

That's how.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜