6.6 Type Conversion and Coercion

In some languages like C, it is possible to convert the type of a program component from one type to another. This is called casting in C and is written as, for example:

int i;
float a;
a = (float) sin((double)i);

Here the sine function is defined as double sin(double), we cast our argument i to type double, so that the compiler is able to generate the type conversion code to be used at the run-time. Again, the variable on the LHS is type float and we have have cast the RHS in that type. In fact, some of such conversions, especially in assignments, are very common and do not require explicitly mentioned type casting. Thus, we could have written the above code segment as:

int  i;
float  a;
a = sin((double)i);

This is called type coercion. Further, we may even drop the cast in the call argument:

int i;
float a;
a = sin(i);

This is called type promotion, i.e., i of type integer is promoted to type double. In both these cases, implicit type casting is involved and the compiler must detect it and insert appropriate type conversion code in the compiled code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.28.107