Converting Data Types

It's usually best to avoid mixing data items of different types in the same expression. You wouldn't normally add a character variable to a floating-point variable, for instance. Some languages, such as QuickPascal, generally treat type mixing as an error. However, the C language gives you the freedom to mix data types when necessary.

For example, since the char and int types both can store whole numbers, there may be times when you have a good reason to add a char value to an int value. When you mix types, QuickC does not issue an error message. Instead, the compiler converts both data items to the same type and then performs the requested operation.

Type conversion can occur in one of two ways. The first way occurs automatically when you combine different types in an expression. You can also use special syntax to intentionally “cast” (convert) one type to another. We'll discuss both methods in the following sections.

Knowing how C converts types will help you to find bugs that result from unintended type clashes and to minimize errors when you deliberately mix types.