Type Casting in C
Type Casting in C
Type Casting refers to changing of the variable data type from one form to another after being initialized. The compiler will automatically change the type of the data into another type if it makes sense.There are two types of Type Casting:
1. Implicit Type Conversion.
2. Explicit Type Conversion.
Implicit Type Conversion.
Implicit type conversion is only known as automatic type conversion. It is done by the computer on it's own without any interference of the user or without triggering anything.
All the data types of the variables are upgraded to the data type of the variable with largest data type.
bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double
Example of Type Implicit Conversion:
/*
Implicit Type Convertion
@uther- Abhishek
*/
#include <stdio.h>
int main()
{
int a=5,c;
char b='z';
float d=a+5; // direct type casting by computer itself
float e;
c=a+b;
/* Here 'z' has be type casted by
the computer to its ASCII value */
e=a+5+d;
/* Here a has been casted from
int to float by the computer itself */
printf(" c = %d",c);
printf(" d = %f ",d);
printf(" e = %f ",e);
}
Output:
c = 127 d = 10.000000 e = 20.000000
Explicit Type Conversion
The conversion of a data type manually by an user from one form to another is known as explicit type conversion.
Syntax :
(<data type>) <vartiable>
Example of Type Explicit Conversion:
/*@uther - Abhishek
(Conversion from int to float)
*/
#include <stdio.h>
int main()
{
int a=5,b=2;
float c1,c2;
c1=(float)a/(float)b; // this will give the result 2.5
c2=a/b; // this will give the result 2
printf(" C1 = %f C2 = %f",c1,c2);
return 0;
}
(Conversion from int to float)
*/
#include <stdio.h>
int main()
{
int a=5,b=2;
float c1,c2;
c1=(float)a/(float)b; // this will give the result 2.5
c2=a/b; // this will give the result 2
printf(" C1 = %f C2 = %f",c1,c2);
return 0;
}
Output:
C1 = 2.500000 C2 = 2.000000
Similarly another manual type castings are also possible.
Comments
Post a Comment