Type Conversion
Type conversion is done to convert a variable of a declared type to some other required type. In language C, value of one data type can be converted to another. Such as an int value can be converted in float, a char value can be converted into int, etc.
The conversion of data types can be done in following ways.
Type conversion in expressions
Type conversion by assignment
Type casting
Type conversion in expressions
An expression is a combination of variables, constants and operators arranged as per the syntax of the language. When two variables of different types appear in the same expression, then lower type variable is automatically converted to higher type variable. Compiler itself performs this automatic conversion.
"Highest" àlong double > double > float > long > int > char à "Lowest"
int a = 5;
float b;
b = 21.5 / a;
In the last statement, the integer variable a first converted to a float and then used in the expression. Here a lower type is being converted to a higher type automatically. Now variable b has 4.3 float values.
Type conversion by assignment
When two variables of different types appear in an assignment expression then the type of the value at the right side of the assignment operator is converted to the type of variable at the left side of the assignment operator and then it is assigned.
int x;
float f = 26.2739;
x=f;
In the last statement, a float variable is assigned to an integer variable. Here the value in f is converted to integer and then assigned to variable x. Now x has value 26.
int x = 24;
float y;
y = x;
In the last statement, an integer variable is assigned to a float variable. Here the value in x is converted to float and then assigned to variable y. Now y has value 24.000000.