how does increment work?

Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
Undefined Behavior and Sequence Points

Ok we all know that i++ increments value by 1 on next line and ++i increments on same line
(please correct me if i am wrong there )
so for a sample statement of c as follows:

int a=0;  
printf("%d , %d",++a,a);  

the expected output should be 1 , 1 but instead it gives 1 , 0 so as one might guess what i am asking here is why does the second linking of i print 0 instead of 1 when the value is already incremented.

So if post increment didn't increment value in the same line then what is the difference between post and pre increment?
edit : changed the name of variable from i to a to avoid grammatical confusion.


You are very wrong in your understanding of the increment operators. i++ increments i , and returns its old value; ++i increments i , and returns the new value. When the actual incrementation takes place is only guaranteed to be after the preceding sequence point, and before the next; in your code, this means before the call to printf .

Beyond that (and largely because of that), if you modify the value of an object, you're not allowed to access it anywhere else without an intervening sequence point, except as needed to determine the new value. You violate this rule, so your code has undefined behavior.


It's undefined behavior. the compiler is allowed to calculate the parameters in any order. your compiler just calculate it from right to left, so the rightest parameter is 0, and the 2nd is 1.

edit: as Seth said, the compiler is only free to change the order of calculating, not to do whatever it wants, so when you don't care about the order you can freely call functions, but you should never assume that one parameter is been calculated before another.


I think your question is not about how increment work. The phenomenon you have observed is about the order of passing parameter to a function. As far as I can remember, this is not defined by c++ standard, so it's a UNDEFINED BEHAVIOR. Meaning different compiler could have different implementation. Eg One compiler could pass parameter from left to right, then a different could pass parameters from right to left.

You can have a better read of Sequence point here: http://en.wikipedia.org/wiki/Sequence_point

链接地址: http://www.djcxy.com/p/73244.html

上一篇: C / C ++后

下一篇: 增量如何工作?