Type Casting in C

Course- C >

Type casting allows us to convert one data type into other. In C language, we use cast operator for type casting which is denoted by (type).

Syntax:

 
  1. (type)value;      

Note: It is always recommended to convert lower value to higher for avoiding data loss.

Without Type Casting:

 
  1. int f= 9/4;  
  2. printf("f : %d\n", f );//Output: 2  

With Type Casting:

 
  1. float f=(float) 9/4;  
  2. printf("f : %f\n", f );//Output: 2.250000  

Type Casting example

Let's see a simple example to cast int value into float.

 
  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000