Manual Type Conversions through Casting

The C language also allows you to force a type conversion that would not otherwise happen, a process known as “casting.” Using casts, it is possible to convert a data item to any C data type.

Sometimes you must use a cast to make the program work properly. When calling the malloc library function, for instance, you should perform a cast on the value that the function returns.

Casts can also make a program more readable. QuickC does most automatic type conversions silently. So if you write a tricky bit of code that relies on automatic conversions, you, or some other programmer, may not notice the conversions later. To make such code more readable—and easier to debug—you can add explicit type casts in places where silent conversions might go unnoticed.

To cast a value to a different type, place the desired type name in parentheses in front of the value. For instance, the statement

f_val = (float)any_val;

casts the value of the variable any_val to type float before assigning it to f_val. Here the type name in parentheses,

(float)

performs the cast. No matter what type any_val has, the cast converts that type to float before assigning it to f_val.

When you cast a variable, the cast affects the value the variable yields, but not the variable itself. Suppose that any_val is an int variable with the value 333. The above cast converts the value 333 to float format before assigning it to f_val. But any_val remains an int variable after the cast.

Remember, you can detect automatic type conversions by setting Warning Level 2 or higher in QuickC and watching for the following warning:

C4051: data conversion

You can then add explicit casts to eliminate the warning where the conversions are desirable. (For more information, see “Automatic Type Conversions”.)