Type Conversion in C

Type Conversion in C


What is Type Conversion ?

Typecasting is conversion of an variable from one data type into another.

Types of Type Conversion :

C type conversion can be classified into two types ~

1. Implicit Type Conversion :

When the type conversion is performed by the compiler automatically, without any external trigger from the user, such type of conversion is known as implicit type conversion or type promotion.

This types conversion takes place when more than one data type is present in an expression.

Implicit type conversion Program :


#include<stdio.h>
int main()
{
	int x;
	for(x=97; x<=122; x++)
	{

	//Implicit casting from int to char
		printf(" %c ", x);
	}
	return 0;
}
Output :
a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  p  q  r  s  t  u  v  w  x  y  z  

//Here, we can see the output as alphabet because,
//the 'x' variable's value is 97 which is ASCII value of 'a'.

2. Explicit Type Conversion :

When the type conversion is performed by the programmer by declaring the data type of the expression of specific type is known as explicit type conversion.

~ The explicit type conversion is also known as Type Casting.
~ Converting the lower value to higher is the ideal way of type casting to avoiding data loss.

Syntax :
(type_name) expression;

//data_type is any valid c data type
//expression may be constant, variable or expression.


Explicit type conversion Program :

#include<stdio.h>
int main()
{
    int x=91, y=47;
    float z;
    
    // Explicit conversion from int to float
    z = (float)x/(float)y;
    printf("Division of %d and %d : %.2f", x, y, z);
    return 0;
}


Output :
Division of 91 and 47 : 1.94