Type Casting in C which conversion of a variable from one type to another type. When type casting is applied on the variable, latest data type is considered by the compiler as the data type of that variable.
Example
[c]int x;
x=(float)8/3;[/c]
In the above example, first the variable x is in integer type and then converted to float type and the result will be in float i.e 2.666.
There are mainly two types of Type Casting in C. They are:
Implicit Type Casting
Explicit Type Casting
Implicit type conversion
Description
The automatic conversion of type performed by the compiler can be called as implicit conversion or type promotion. The compiler converts all operands into the data type of the largest operand.
The variable to be converted will be always on the left side of arithmetic operator. The data type of highest operand is given to all the operands. There is no loss of data by using implicit conversion.
Implicit conversion focuses mainly on conversion from "low data type to high data type".
Conceptual
figure
Example
[c]
int a;
float b,c;
c=a+b; // int is converted to float[/c]
Explicit type conversion
Description
Explicit type of conversion is done by the programmer by posing the data type of the expression of specific type. The conversion focuses mainly on conversion from "high data type to low data type". There will be loss of data by using explicit conversion.
Explicit Type casting in C is done in the following way.
(data_type)expression;
where, data_type is any valid c data type, and expression may be constant, an expression or a variable.
To avoid the loss of information while performing the explicit conversions following rules have to be followed.
All integer types should be converted to float.
All float types should be converted to double.
All character types should be converted to integer.
Example - 1
[c]
float a=1.23;
int b=(int)a;
[/c]
In the above example, float value is 1.23. When float is converted to integer data type, only '1' will be the output. The remaining '0.23' is lost due to explicit conversion.
Example - 2
[c]
#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
short p;
p = (short) i; // Explicit conversion
printf("Explicit value is %d",p);
getch();
}[/c]
Output:
[c]
Explicit value is 20[/c]
Summary
Key Points
Type Casting in C helps in conversion of variable type.
Implicit conversion is performed from low data type to high data type and Explicit conversion functions in reverse to implicit.
Programming
Tips
When a result is assigned to variable of different type, there may be a loss of data during conversion. Be careful about it.