i
or cnt
by convention), such as i++
.How the Increment and Decrement Operators Affect Numbers
Operator | Symbol | Purpose | Example | Result |
---|---|---|---|---|
Increment | ||||
Decrement |
The interesting and sometimes confusing thing about the increment and decrement operators is that they have two forms – prefix and postfix notation – which act slightly differently. Prefix notation is when the operator ("++" or "--") is in front of the number or variable – for instance,
--i
or ++cnt
. Postfix notation is when the operator ("++" or "--") is placed after the number or variable – for instance, i++
or cnt--
.When used in an expression (equation), prefix notation means the increment or decrement takes place before the number or variable is used. In postfix notation, the original value of the number or variable is used and then the increment or decrement takes place. This is easiest to understand by looking at how it works.
Prefix Notation | Postfix Notation | |
---|---|---|
Code | a=4 b=++a + 2 | a=4 b=a++ + 2 |
Result | The increment takes place first resulting in the following values: a=5 b=7 | The addition take place first resulting in the following values: a=5b=6 |
Prefix and postfix notation can be confusing, however, a few things make it easier. In the vast majority of cases, the increment and decrement operators are used on their own or in parenthesis. When the increment and decrement operators are used on their own (as they often are when used as loop counters), the prefix and postfix versions work identically. The same is true when they are used in parenthesis. To avoid confusing yourself or other people reading your code, it's a good idea to use increment and decrement operators in expressions sparingly and with parenthesis whenever possible.