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:
Click here to view code image
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.
Typecasting: Hollywood Could Take Lessons from C
Two kinds of typecasting exist: the kind that directors of movies often do (but we don’t 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 converts age to a
float value of 6.0:
(float)age;
If you were using age in an expression with other floats, you should typecast age to float to maintain
consistency in the expression.
Tip
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.