Auto-increment (++) and auto-decrement (--)
To add or subtract one, 1, to or from a variable, use the autoincrement, ++, or autodecrement, , operator. These operators add or subtract 1 from the value to which they are applied. Thus, i++ is a shortcut for i += 1, which is a shortcut for i = i + 1.
These operators can be used before, as a prefix operator, or after, as a postfix operator, their variables. If they are used before a variable, it is altered before it is used in a statement, and if used after, the variable is altered after it is used in the statement. The following lines demonstrates prefix and postfix operations.
i = 4; |
i is 4 |
|
j = ++i; |
j is 5, i is 5 |
(i was incremented before use) |
j = i++; |
j is 5, i is 6 |
(i was incremented after use) |
j = --i; |
j is 5, i is 5 |
(i was decremented before use) |
j = i--; |
j is 5, i is 4 |
(i was decremented after use) |
i++; |
i is 5 |
(i was incremented) |