What is Type Conversion? Explain its Types?


Converting one data into another is called type conversion. In ‘C’ language type conversions are done in 2 ways.

1. Implicit type conversion.

2. Explicit type conversion.

1. Implicit type conversion:

The lower data is converted into higher data.

Ex:– Integer  value is converted into float value. In case of implicit type convention data is not loosed.

Ex:– int x = 10;
        printf(“%f”, x);   
        out put - 10.000000

It is called arithmetic type conversion.

C permits mixing of constants & variables of different types in an experiment. C automatically converts any intermediate values to the proper type. This automatic conversion is known as implicit type conversion.

If the operands are of different types the lower type is automatically converted to the higher type before the operation proceeds. The result is of higher type.

The final result of an expression is converted to the type  of the variable  on the left of the assignment sign before assigning the value of it. However, the following changes are introduced during the final assignment.

1. float to int causes truncation of the fractional part.

2. double to float causes round of digits.

3. long int to int causes dropping of the excess higher order bits.


type conversion



2. Explicit type conversion:

Higher data is converted into lower data.

Ex:– float data is converted into integer data.

Ex:–  float  x = 10.25;
            y = (int)x;
           out put = 10.

In the above ex. It truncates the fractional data. That means it causes loss of data.

Ex:– x = (int) 21.75/(int)4.3 it takes 21/4  gives 5.

However, these are instances when we wait to force a t.c in a way that is different from the automatic type conversion consider the following example.

#include < stdio.h >
#include < conio.h >
main()
{
 int x, y;
 float a;
 x = 6, y = 4;
a = x/y;
printf(“\n result %f”, a);
}

In the above example  the output is 1.000000 but not 1.5 because 6&4 are of integer 1, this 1 is stored in the variable ‘a’. That is conved to 1.000000( because of float data).

Sometimes we require to force the compiler explicitly converts the value of an expression from one data to another data is called type casting (or) explicit type conversion.

This is done by using cast operator as follows :

Syntax: (type–name) expression;

Where type–name is one of the standard C data types. The expression may be constant, variable or an expression.

Ex:–

#include < stdio.h >
#include < conio.h >
main()
{
 int x, y;
 float a;
 x = 6, y = 4;
a = (float)x/y;
printf(“\n result %f”, a);
}

Note that the value of x does not permanently change as a result of type casting. Rather it is the value of the expression. That undergoes in type conversion whenever the cast operator appears.


Related

C Language 8348369573388241156

Post a Comment

emo-but-icon

item