14

Coercion or Type-Casting

C is one of the few languages to allow coercion, that means to force a variable of one type to be another type. C allows this using the cast operator (). So:

int integernumber;

float floatnumber=9.87;

assigns 9 to integernumber. (the fractional part is thrown away)

And:

int integernumber=10;

float floatnumber;

assigns 10.0 to floatnumber.

Coercion can be used with any of the simple data types including char, so:

int integernumber;

char letter='A';

assigns 65 (the ASCII code for `A') to integernumber.

Some typecasting is done automatically - this is mainly with integer compatibility.

A good rule to follow is: If in doubt cast.

Another use is the make sure division behaves as requested: If we have two integers internumber and anotherint and we want the answer to be a float then :

eg.

floatnumber = (float)internumber/(float)anotherint;

ensures floating point division.


drago@scri.fsu.edu
Jan. 1997