Post/pre increments in 'printf' [duplicate]
Possible Duplicates:
Output of multiple post and pre increments in one statement Post-increment and pre-increment in 'for' loop
The following code snippet
int i=0;
printf("%d %d",i++,i++);
gives the output
1 0开发者_开发问答
I can understand that, but the following
int i=0;
printf("%d %d",++i,++i);
gives the output
2 2
Can someone explain me the second behavior?
Both printfs invoke undefined-behavior. See this : Undefined behavior and sequence points
Quoted from this link:
In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant.
For newbies : Don't ever try to modify values of your variables twice or more in a function call argument-list. For details, click here to know what it means. :-)
They're both undefined behaviour. Modifying the variable i
more than once is undefined. Also, C++ or C? You need to make up your mind as the behaviour of pre-increment I believe is different between them.
You got what called 'undefined behaviour', because you are changing the same variable more than once between sequence points. Another compiler can give you different results.
精彩评论