Type Conversion In C Language

10 February 20120 comments

In some situations we may declare some variables of one type and require the result in another data type.In these situations type conversion is used.

Type conversion can be done in two ways:
  • Automatic Type Conversion
  • Type casting
Automatic Type Conversion :

In case of two different data types present in an expression lower size data type must be automatically converted into the higher size data type before the operation proceeds.For example: If there is an operation between int and float , the result will be in float and so on.

Program To Demonstrate Automatic Type Conversion

  1. #include<stdio.h>
  2. #include<conio.h>
  3. main( )
  4. {
  5.     int i;
  6.     float f;
  7.     double d;
  8.     clrscr( );
  9.     printf("Enter the value of i in integer");
  10.     scanf("%d",&i);
  11.     printf("Enter the value of f in float");
  12.     scanf("%f",&f);
  13.     d=i*f;
  14.     printf("\n Value of d=%lf",d);
  15.     getch( );
  16. }
Enter the value of i in integer 10
Enter the value of f in float 5.75
Value of d = 57.500000

Type casting

As type conversion is automatically done by the compiler , the type casting can be done by the user as per the requirements. Type casting can be done in the following general form
                                                           (data type) expression
e.g   ((int(x+y+z))/2

In this example if x+y+z is to be calculated as float because of any of them to be float , and we want it to be converted into int before dividing it by 2 then we use this type casting.

Share this article :

Post a Comment

 
Copyright © 2011. All Compiler - All Rights Reserved