C Tutorial C References

C - Type Casting



The type casting is a method of converting the value of one data type to another data type. It is also known as type conversion. In C, there are two kinds of conversions, which are given below:

  • Implicit Type Casting
  • Explicit Type Casting

Implicit Type Casting

The implicit type casting happens automatically when converting a smaller data types to larger data types. The compiler implicitly typecast the smaller data types to the larger data types. No data will be lost in this process.

C Implicit Casting

Example

The example below shows how the implicit type casting is done in C.

#include <stdio.h>
 
int main (){ 
  char num_char = 65;

  //implicit casting
  short num_short = num_char;
  int num_int = num_short;
  long num_long = num_int;
  float num_float = num_long;
  double num_double = num_float;
  long double num_long_double = num_double;

  //printing variables
  printf("num_char = %c\n", num_char); 
  printf("num_short = %i\n", num_short);
  printf("num_int = %i\n", num_int);
  printf("num_long = %li\n", num_long);
  printf("num_float = %f\n", num_float); 
  printf("num_double = %lf\n", num_double); 
  printf("num_long_double = %Lf\n", num_long_double); 
}

The output of the above code will be:

num_char = A
num_short = 65
num_int = 65
num_long = 65
num_float = 65.000000
num_double = 65.000000
num_long_double = 65.000000

Explicit Type Casting

The explicit type casting does not happen automatically. It is performed manually by calling the compiler explicitly to typecast the larger data types into the smaller data types. There might be a data loss in this process.

C Explicit Casting

This is also known as cast notation. The syntax of this method is given below:

(new_type)expression;

Example

The example below shows how the perform explicit type casting.

#include <stdio.h>
 
int main (){    
  long double num_long_double = 68.75;

  //explicit casting
  double num_double = (double) num_long_double;
  float num_float = (float) num_double;
  long num_long = (long) num_float;
  int num_int = (int) num_long;
  short num_short = (short) num_int;
  char num_char = (char) num_short;

  //printing variables
  printf("num_long_double = %Lf\n", num_long_double); 
  printf("num_double = %lf\n", num_double); 
  printf("num_float = %f\n", num_float); 
  printf("num_long = %li\n", num_long); 
  printf("num_int = %i\n", num_int); 
  printf("num_short = %i\n", num_short); 
  printf("num_char = %c\n", num_char);  
}

The output of the above code will be:

num_long_double = 68.750000
num_double = 68.750000
num_float = 68.750000
num_long = 68
num_int = 68
num_short = 68
num_char = D