Type conversion and Type Casting

 Type conversion

Type conversion  in C is the process of converting one data type to another.  The type Conversion is only performed to those data types where conversion is possible. Type conversion is performed by a compiler. In type Conversion data type can be convert lower rank into higher rank.




Implicit Type Conversion

These conversion are done by the compiler according to some predefine rules of C language. The two types of implicit conversions are automatic type conversion and type conversion in assignment.

Generally take place when in an expression more than one data type is present. In such condition type conversion(type promotion) takes place to avoid loss of data.

All the data types of the variable are promoted to the data type of the variable with the largest data type.

char-> short int-> int-> long int-> float-> double-> long->double

Implicit type conversion is also called automatic type conversion. some of its few occurrences are mention below :

* Conversion rank
* Conversion in assignment expressions 
* Conversion in other Binary expression
* Promotion
* Demotion

Program to demonstrate type promotion of implicit type conversion 


#include <stdio.h>
int main()
{
    /* Implicit type conversion*/
    int a=15;
    char b='a';
    int c=a+b;
    printf("c=%d",c);
    return 0;
}

Output:
c=112

Explicit type Conversion or Type casting

There may be certain situation where implicit conversions may not solve our purpose. for example-

float c;
int a=20 ,b=3;
c=a/b;

The value of c will be 6.0 instead of 6.66.

Typecasting in C is the process of converting one data type to another data type by the programmer using the casting operator during program design.

syntax:
    
destination_datatype = (target_datatype) variable;

( ) : is a casting operator .

 /*program to illustrate the use of cast operator*/

#include <stdio.h>
int main()
{
    /*  type casting*/
    int a=20,b=3;
    float c,d;
    c=a/b;
    printf("c=%f\n",c);
    d=(float)a/b;
    printf("d=%f\n",d);
    return 0;
}

Output:
c=6.000000
d=6.666667

Comments

Popular posts from this blog

18 Amazing programs in C.