Typeconversion and Typecasting in C

Written by

Pooja Rao

Type-conversion and Typecasting means conversion of value of an identifier/variable from one data type to another either implicitly that is automatically by C and explicitly that is forced conversion.

Type conversion:

  • Type conversion refers to implicit conversion, that is C automatically converts any intermediate value in an operation to the proper type so that the expression can be evaluated appropriately.
  • Lower data type is automatically promoted to higher data type.
  • The result will be depicted in higher data type.
  • Example: If one operand is int and other is float then int is auto converted to float.
  • The conversion hierarchy is as follows:


 
The hierarchy is from low to high so that no information is lost.

Example:

#include <stdio.h>
int main()
{
int a = 10;
float b,c;
b=5.0;
c= (a/b);
 
printf("Result: %.2f", c);
 
return 0;
}

 

Output:

Result: 2.00

As seen above, although ‘a’ was of integer data type, due to type conversion, the resultant answer was calculated in float ; after a was converted to 10.0 and the expression evaluated.
 
It is very essential to keep in mind the order of conversion, as otherwise the resultant answer will not be properly evaluated. If we downgrade from higher data type to lower one , then there will be loss of bits. For instance if we move from float to int, the decimal part will get omitted.

Typecasting:

  • Typecasting is explicit converting from one data type to the other. It is also called as forced or manual conversion.
  • Generally used when there is a need to convert higher order data types to lower order ones. For instance, float to int.
  • Basically , we make a variable of one data type act as a variable belonging to the other data type.
  • Syntax: (data-type)expression;
  • We place the destination data type enclosed  in parentheses() followed by the expression/ variable.
  • It is usually done to get the correct result, even if the conversion might be from a lower to higher data type.

Example:

#include <stdio.h>
int main()
{
int a = 10, b = 3;
float c, d;
c = a/b;
d = (float)a/b;
printf("Result C: %.2f\n", c);
printf("Result D:%.2f", d);
return 0;
}

 

              Output:

Result C: 3.00
Result D: 3.33

 
As seen in the above example, when the above division operation is performed between integers for result C, since the resultant variable is float both of the
variables ‘a’ and ‘b’ are converted automatically to float ; due to type conversion.
 
However, the decimal part after division is performed gets truncated as they are
originally integer data types. That is without type casting the answer is C = 3.00.
Since we typecasted the result in second case for D, (a/b) into float , the decimal
values were also  retained, thus D = 3.33.

Typeconversion and Typecasting in C