C Type Casting

 In a c programming language, the data conversion is performed in two different methods as follows...

  • Type Conversion
  • Type Casting
Type Conversion
 

The type conversion is the process of converting a data value from one data type to another data type automatically by the compiler. Sometimes type conversion is also called implicit type conversion. The implicit type conversion is automatically performed by the compiler.
For example, in c programming language, when we assign an integer value to a float variable the integer value automatically gets converted to float value by adding decimal value 0. And when a float value is assigned to an integer variable the float value automatically gets converted to an integer value by removing the decimal value

int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;

i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i

x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x

i = ch ; =======> Here the ASCII value of A (65) is assigned to i  

 

Example 

#include <stdio.h>
#include <conio.h>
int main() {
   int i = 18 , j = 10;
   float x = 19.90 ;
   char ch = 'A' ;
   
   i = x ;
   printf("i value is %d\n",i);
   x = j ;
   printf("x value is %f\n",x);
   i = ch ;
   printf("i value is %d\n",i);      
   return 0;
   getch();
}

Output 


 

Typecasting
 
Typecasting is also called an explicit type conversion. Compiler converts data from one data type to another data type implicitly. When compiler converts implicitly, there may be a data loss. In such a case, we convert the data from one data type to another data type using explicit type conversion. To perform this we use the unary cast operator. 

Syntax
 (dataType)value;
 
Note:
It is always recommended to convert the lower value to higher for avoiding data loss.
 
 
Without Type Casting:
 
Example
 
 #include <stdio.h>
#include <conio.h>
int main() {
   int f= 9/4;  
   printf("Value of f : %d\n", f );    
   return 0;
   getch();
}
 
Output
 

 
With Type Casting:
 
Example
 
#include <stdio.h>
#include <conio.h>
int main() {
   float f= (float)9/4;  
   printf("Value of f : %f\n", f );    
   return 0;
   getch();
}
 
Output





No comments:

Post a Comment