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

(Romina) #1

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:


Click here to view code image


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.


Warning

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.

You can typecast an entire expression. The following statement typecasts the result of an expression
before assigning it to a variable:


Click here to view code image


value = (float)(number - 10 * yrsService);

The parentheses around the expression keep the typecast from casting only the variable number. C
does perform some automatic typecasting. If value is defined as a float, C typecasts the
preceding expression for you before storing the result in value. Nevertheless, if you want to clarify
all expressions and not depend on automatic typecasting, go ahead and typecast your expressions.


The Absolute Minimum
The goal of this chapter was to teach you additional operators that help you write C
programs. You also learned to use typecasting if you want to mix variables and
constants of different data types. Key concepts from this chapter include:


  • 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.

  • 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.

Free download pdf