Type Casting in C:

Type casting allows you to change the data type of a variable to other data type.

Types:

  • Implicit Type Casting
  • Explicit Type Casting

Implicit Type Casting:

In case of implicit type casting, we do not need a type casting function to do type casting like in case of explicit type casting. It occurs automatically by the programming language without any explicit instruction by the programmer.
int x = 10;
float y = x;

Note: Implicit type casting is also called Automatic Type Conversion.


Explicit Type Casting:

In case of explicit type casting, programmer has to specify the conversion from one data type to another explicitly. We perform explicit type casting using different type casting functions
int x;
y = float(x);

Note: Explicit type casting is also called Manual Type Conversion.


More Examples of Explicit Type Casting:

typecasting.c
#include <stdio.h>

int main() {
  float num1 = 10.3;
  float num2 = 3.1;
  // The result is a float, convert it to int
  int sum = (int) 10 + 3;

  printf("%d", sum);
  return 0;
}

When we store data in variables, they are stored in memory. We can perform different types of computations or operations on variables. For this purpose, the variables must have compatible data types. This is the reason why we do type casting. In type casting, we assign the value of one data type to another.

typecasting.c
#include <stdio.h>

int main() {
  int num1 = 10;
  int num2 = atoi ("3");
  int sum = num1 + num2;

  printf("%d", sum);
  return 0;
}

Different Type Casting Functions in C:

In C language, there are five built-in type casting functions which are given below:
  • atoi(): It converts string data tyoe to int data type.
  • atbol(): It converts string data type into long data type.
  • ltoa(): It converts long data type to string data type.
  • itoba(): It converts int data type to sring data type.
  • atof(): It converts string data type to float data type.