10. What Else Can I Do with Expressions?

Combine Operators and Give Typecasts

image

As you can see from the Order of Operators table on the tear-out card (at the beginning of the book), C has a rich assortment of operators. C has many operators that help C keep its command vocabulary small. There aren’t many commands in C, but there are a lot more operators than in most other programming languages; whereas most computer programming languages have relatively few operators and lots of commands, C retains its succinct nature by providing many powerful operators.

This chapter explores a few more operators that you’ll need as you write programs. The compound assignment operators and the typecast operator provide the vehicles for several advanced operations.

Compound Assignment

There will be many times in your programs when you have to change the value of a variable. Until now, all variables have been assigned values based on constant literal values or expressions. However, there will often be times when you must update a variable.

Suppose your program had to count the number of times a profit value goes below zero. You would need to set up a counter variable. A counter variable is a variable that you add one to when a certain event takes place. Every time a profit value goes negative, you might do this:

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

Warning

image

In math, nothing can be equal to itself plus 1! With computers, though, the previous assignment statement adds 1 to lossCount and then assigns that new value to lossCount—in effect adding 1 to lossCount’s value. Remember that an equals sign means “take whatever is on the right of the equals sign and store that computed value in the variable on the left.”

The following program is simple but prints the numbers from 1 to 5 using a counter assignment statement before each printf():

image

The following lines show the program’s output. Notice that ctr keeps increasing (in computer lingo, it’s called incrementing) by one with each assignment statement

image

By subtracting instead of adding, you can decrement a variable’s value in a similar fashion (such as when you want to decrease totals from inventories as products are sold).

There will be other times when you’ll need to update a variable by adding to a total or by adjusting it in some way. The following assignment statement increases the variable sales by 25 percent:

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

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 one). 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.

Clue

image

Chapter 15, “Are There Other 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.

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

and

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

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

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

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

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

Note

image

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.

Table 10.1. Compound assignment operators.

image

Note

image

The dispCard() function in the Blackjack game in Appendix B uses a compound addition operator to update the card count depending on the value of the last card drawn.

Watch That Order!

Look at the order of operators table and locate the compound assignment operators. You’ll see that they have very low precedence. The +=, for instance, several levels lower than the +.

Initially, this might not sound like a big deal. (Actually, maybe none of this sounds like a big deal. If so, great! C should be easier than a lot of people would have you think.) The order of operators table can haunt the unwary C programmer. Think about how you would evaluate the second of these expressions:

total = 5;
total *= 2 + 3;  /* Updates the total variable */

At first glance, you might think that the value of total is 13 because you learned earlier that multiplication is done before addition. You’re right that multiplication is done before addition, but compound multiplication is done after addition according to the order of operators. Therefore, the 2 + 3 is evaluated to get 5, and then that 5 is multiplied by the old value of total (which also happens to be 5) to get a total of 25, as Figure 10.1 points out.

Figure 10.1. The compound operators reside on a low level.

image

Typecasting: Hollywood Could Take Lessons from C

There are two kinds of typecasting: the kind that directors of movies often do (but we’ll not cover that here) and also C’s typecasting. A C typecast temporarily changes the data type of one variable to another. Here is the format of a typecast:

(dataType)value

The dataType can be any C data type such as int, or float. The value is any variable, literal, or expression. Suppose that age is an integer variable that holds 6. The following:

(float)age

converts age to a float value of 6.0. If you were using age in an expression with other floats, you should typecast age to float to maintain consistency in the expression.

Note

image

Because of some rounding problems that can automatically occur if you mix data types, you’ll have fewer problems if you explicitly typecast all variables and literals in an expression to the same data type.

Never use a typecast with a variable on a line by itself. Typecast where a variable or an expression has to be converted to another value to properly compute a result. The preceding typecast of age might be represented like this:

salaryBonus = salary * (float)age / 150.0;

age does not change to a floating-point variable! age is changed only temporarily for this one calculation. Everywhere in the program that age is not explicitly typecast, it is still an int variable.

Clue

image

If you find yourself typecasting the same variable to a different data type throughout a program, you might have made the variable the wrong type to begin with.

Rewards

image

• Use compound assignment operators when updating variable values.

• Use compound assignment operators to eliminate a few typing errors and to decrease your program-writing time.

• Put a data type in parentheses before a variable, expression, or data value you want to typecast.

Pitfalls

image

• Don’t mix data types. Instead, typecast data so that it is all the same type before evaluating it.

• Don’t ignore the order of operators! The compound operators have low priority in the table and are done after almost every other operator finishes.

In Review

The goal of this chapter was to teach you additional operators that help you write C programs. Use the compound operators when you want to change the value of a variable. You don’t have to repeat the variable name on both sides of the equals sign because a compound operator understands that you want to update the variable’s value. (This saves you lots of typing and potential errors if you use long variable names such as costOfGoodsSold.)

If you want to mix variables and constants of different data types, use typecasting to produce uniform data types in expressions. Although C will typecast automatically, you won’t always like the results. C might convert float to int when you wanted everything to remain float. Typecasting becomes especially critical later when you write more advanced programs that use pointers and structures.

Code Example

image

Code Analysis

The code first asks the user for his or her age. Because people rarely enter fractional ages, the age value is stored in an integer variable. The age is then divided by 7.0 to get the corresponding age in dog years. (A year to a dog is like seven years to a person, which makes you wonder how Lassie has lived since the 1950s.)

Because the division produces a floating-point result, the typecast ensures that age is converted to float before the calculation is performed. Making your data types consistent is very important as you move into more advanced programming.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset