Node:Confusing foo++ and ++foo, Next:, Previous:Confusion of = and ==, Up:Run-time errors



Confusing foo++ and ++foo

In many cases, the forms foo++ and ++foo are identical. However, if they are hidden inside another statement, there can be a subtle difference. For example:

my_array [++my_index] = 0;

The code ++my_index cause my_index to be incremented by 1 before the assignment takes place, whereas my_index++ would have cause my_index to be incremented after the assignment takes place. Sometimes you'll want one and sometimes the other. If you find that your program is miscalculating by a difference of 1 (this is called an off-by-one bug and is quite common), a prefix or postfix ++ could be the cause. The same holds for other prefix and postfix operators, such as --.