2. What is Type casting
Type casting is a way to convert a variable from one data type to another data type.
For example, if you want to store a long value into a simple integer then you can type
cast long to int. You can convert values from one type to another explicitly using the
cast operator.
It is best practice to convert lower data type to higher data type to avoid data loss.
Data will be truncated when higher data type is converted to lower. For example, if float
is converted to int, data which is present after decimal point will be lost.
(type_name) expressioncast operator:
3. Example
#include <stdio.h>
void main ()
{
float x;
x = 7/5;
printf("%f n",x);
}
#include <stdio.h>
void main ()
{
float x;
x = (float) 7/5;
printf("%f n",x);
}
Output:
1.000000
Press any key to continue . . .
Output:
1.400000
Press any key to continue . . .
No Typecasting in this Example Typecasting
Here is the difference between this result
this result is not correct actually .Here typecasting is necessary
So after type casting get the correct result
4. Types of typecasting in C Programming
1. Implicit conversion
Implicit conversions do not required any operator for converted . They are
automatically performed when a value is copied to a compatible type in program.
2. Explicit conversion
Explicit conversions required cast operator for converted . They are not
automatically performed when a value is copied to a compatible type in program.
5. Example
#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
float p;
p=i; // implicit conversion
printf("implicit value is %f n",p);
}
#include<stdio.h>
void main()
{
int i=20;
short p;
p = (short) i; // Explicit conversion
printf("Explicit value is %d n",p);
}
implicit value is 20.000000
Press any key to continue . . .
Explicit value is 20
Press any key to continue . . .
1. Implicit conversion 2. Explicit conversion
6. The usual arithmetic conversions are implicitly performed to cast their values in
a common type
Usual Arithmetic Conversion
Short/char int
Unsigned
int
long
Unsigned
long
floatdouble
Long
double
Unsigned
long long