C Type Casting

In C programming language type casting allows us to convert one data type into another. In simple words type casting is a way to convert a variable from one data type to another data type.

We can convert the values from one type to another explicitly using the cast operator. The syntax is as follows :

Syntax :
 (type_name) expression;
Where :
  • type_name is name of the data type we want to convert.
  • expression is the data (value or variable that contains value) which we want to convert or typecast.
Example :
 (float)100;
For example suppose we have a integer value, and we want to store or convert that value into float, then the statement for typecasting is :
int num = 12;
float val;
val = (float)num;
or
float val;
val = (float)12;
Example Code :
#include <stdio.h>

int main() {
  int num = 12;
  float val;
  val = (float)num;
  printf("The number is : %.2f\n", val);
  return 0;
}
Output :

The number is : 12.00

Lets see another example of type casting.

In below c program the division of 20/7 is stored on the floating point variable num. Now lets look at the example :

Without Typecasting
#include <stdio.h>

int main() {
  float num;
  num = 20/7;
  printf("%f\n", num);
  return 0;
}
Output :

2.000000

With Typecasting :
#include <stdio.h>

int main() {
  float num;
  num = (float)20/7;
  printf("%f\n", num);
  return 0;
}
Output :

2.857143

Note : It's best practice to convert lower data type to higher data type to avoid data loss. Data will be truncated when higher data type is converted to lower. For example, if float is converted to int, data which is present after decimal point will be lost.

Inbuilt Typecast Functions in C Language :

There are various inbuilt typecasting functions available in C language which performs data type conversion from one type to another. Some of them are as follows :

Typecast function Description
atoi() Converts string to int
itoa() Converts int to string
atof() Converts string to float
atol() Converts string to long
ltoa() Converts long to string

Next Topic :