C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

C provides several compound operators that let you update a variable in a manner similar to the
methods just described (incrementing, decrementing, and updating by more than 1). However, instead
of repeating the variable on both sides of the equals sign, you have to list the variable only once. As
with much of C, some examples will help clarify what is done with the compound operators.


Note

Chapter 15, “Looking for Another Way to Create Loops,” shows you how the for
statement makes updating variables easier.

If you want to add 1 to a variable, you can use the compound addition operator, +=. These two
statements produce the same result:


Click here to view code image


lossCount = lossCount + 1; /* Adds 1 to lossCount variable */

and


Click here to view code image


lossCount += 1; /* Adds 1 to lossCount variable */

Instead of multiplying sales by 1.25 and then assigning it to itself like this:


Click here to view code image


sales = sales * 1.25; /* Increases sales by 25 percent */

you can use the compound multiplication operator, *=, to do this:


Click here to view code image


sales *= 1.25; /* Increases sales by 25 percent */

Tip

The compound operators are quicker to use than writing out the entire assignment
because you don’t have to list the same variable name on both sides of the equals sign.
Also, the compound operators reduce typing errors because you don’t have to type the
same variable name twice in the same statement.

Table 10.1 lists all the compound assignment operators and gives examples of each. All the operators
you’ve seen so far in this book, from addition through modulus, have corresponding compound
operators.

Free download pdf