What is Type Conversion in C Programming?

Type conversion means, conversion of one type to another.

There are two types of type conversion, they are

  • Implicit type conversion
  • Explicit type conversion

Hierarchy of Type Conversion

The priority grows higher from bottom to top i.e. Char short int has the lowest priority and Long double has the highest priority.


Implicit Type Conversion

The compiler performs this type of conversion on its own. It is also known as “Automatic type conversion”. The compiler does it when there is more than one data type. Here either promotion or demotion happens. The promotion means conversion to a higher type and demotion means conversion to a lower type.

Example

#include<stdio.h>
int main()
{
  int a=4;
  float b=4.5,c;
  printf("Type conversion happens as follows \n");
  c=a+b;
  printf("Result is:%f \n",c);
  return 0;
}

Code Explanation

In the above code, the operand ‘a’ is int type and operand ‘b’ is float type. As there are two data types in expression, the compiler converts the result into a higher data type. The result is being stored in float type.


Explicit Type Conversion

Explicit type conversion is done by the user explicitly by prefixing the operand or an expression with datatype to be converted. It is also called typecasting. In an implicit type conversion, there is a possibility of a loss of data. For example when signed is converted into unsigned, signs are lost. To overcome this explicit type conversion is used.

Syntax

(datatype)expression

Example

#include<stdio.h>
int main()
{
  int a=2,b=7,c=9;
  float r;
  r=(float)a+b+c/2;
  printf("The result is %f",r);
  return 0;
}

Code explanation

In the above program, the result is of a higher data type that’s why the expression is converted into float type.


People also ask for

Which type of conversion is not accepted?

Conversion of float to pointer is not allowed.

How type conversion is done in c?

The compiler performs the implicit type of conversion on its own. Explicit type conversion is done by the user explicitly by prefixing the operand or an expression with datatype to be converted.