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?
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?
$ 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.
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.
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.
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.