C Programming/Typecasting

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Type conversion or typecasting refers to changing an entity of one data type into another.

[edit] Implicit type conversion

Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler. In a mixed-type expression, data of one or more subtypes can be converted to a supertype as needed at runtime so that the program will run correctly. For example, the following is legal C language code:

double  d;
long    l;
int     i; 
 
if (d > i)      d = i;
if (i > l)      l = i;
if (d == l)     d *= 2;

Although d, l and i belong to different data types, they will be automatically converted to equal data types each time a comparison or assignment is executed. This behavior should be used with caution, as unintended consequences can arise. Data can be lost when floating-point representations are converted to integral representations as the fractional components of the floating-point values will be truncated (rounded down). Conversely, converting from an integral representation to a floating-point one can also lose precision, since the floating-point type may be unable to represent the integer exactly (for example, float might be an IEEE 754 single precision type, which cannot represent the integer 16777217 exactly, while a 32-bit integer type can). This can lead to situations such as storing the same integer value into two variables of type int and type single which return false if compared for equality.

[edit] Explicit type conversion

Explicit type conversion manually converts one type into another, and is used in cases where automatic type casting doesn't occur.

double d = 1.0;
 
printf ("%d\n", (int)d);

In this example, d would normally be a double and would be passed to the printf function as such. This would result in unexpected behaviour, since printf would try to look for an int. The typecast in the example corrects this, and passes the integer to printf as expected.

Explicit type casting should only be used as required. It should not be used if implicit type conversion would normally make the correction.