< Previous | Contents | Next >

Using Increment and Decrement

Operators

Next, I use the increment operator (þþ) which increases the value of a variable by one. I use the operator to increase the value of lives twice. First I use it in the following line:

þþlives;

Then I use it again in the following line:

livesþþ;

Each line has the same net effect; it increments lives from 3 to 4.

As you can see, you can place the operator before or after the variable youre incrementing. When you place the operator before the variable, the operator is called the prefix increment operator; when you place it after the variable, its called the postfix increment operator.

At this point, you might be thinking that theres no difference between the postfix and prefix versions, but youd be wrong. In a situation where you only increment a single variable (as you just saw), both operators produce the same final result. But in a more complex expression, the results can be different.

To demonstrate this important difference, I perform a calculation that would be appropriate for the end of a game level. I calculate a bonus based on the number

28 Chapter 1 n Types, Variables, and Standard I/O: Lost Fortune


of lives a player has, and I also increment the number of lives. However, I perform this calculation in two different ways. The first time, I use the prefix increment operator.

int bonus = þþlives * 10;

The prefix increment operator increments a variable before the evaluation of a larger expression involving the variable. þþlives * 10 is evaluated by first incrementing lives, and then multiplying that result by 10. Therefore, the code is equivalent to 4* 10, which is 40, of course. This means that now lives is 4 and bonus is 40.

After setting lives back to 3, I calculate bonus again, this time using the postfix increment operator.

bonus = livesþþ * 10;

The postfix increment operator increments a variable after the evaluation of a larger expression involving the variable. livesþþ * 10 is evaluated by multi- plying the current value of lives by 10. Therefore, the code is equivalent to 3 * 10, which is 30, of course. Then, after this calculation, lives is incremented. After the line is executed, lives is 4 and bonus is 30.

Cþþ also defines the decrement operator, . It works just like the increment operator, except it decrements a variable. It comes in the two flavors (prefix and postfix) as well.