When variables and constants of different types are combined in an expression then they are converted to same data type. The process of converting one predefined type into another is called type conversion.
Type conversion in c can be classified into the following two types:
Implicit Type Conversion
When the type conversion is performed automatically by the compiler without programmers intervention, such type of conversion is known as implicit type conversion or type promotion.
The compiler converts all operands into the data type of the largest operand.
The sequence of rules that are applied while evaluating expressions are given below:
All short and char are automatically converted to int, then,
- If either of the operand is of type long double, then others will be converted to long double and result will be long double.
- Else, if either of the operand is double, then others are converted to double.
- Else, if either of the operand is float, then others are converted to float.
- Else, if either of the operand is unsigned long int, then others will be converted to unsigned long int.
- Else, if one of the operand is long int, and the other is unsigned int, then
- if a long int can represent all values of an unsigned int, the unsigned int is converted to long int.
- otherwise, both operands are converted to unsigned long int.
- Else, if either operand is long int then other will be converted to long int.
- Else, if either operand is unsigned int then others will be converted to unsigned int.
It should be noted that the final result of expression is converted to type of variable on left side of assignment operator before assigning value to it.
Also, conversion of float to int causes truncation of fractional part, conversion of double to float causes rounding of digits and the conversion of long int to int causes dropping of excess higher order bits.
Explicit Type Conversion
The type conversion performed by the programmer by posing the data type of the expression of specific type is known as explicit type conversion.
The explicit type conversion is also known as type casting.
Type casting in c is done in the following form:
where, data_type is any valid c data type, and expression may be constant, variable or expression.
The following rules have to be followed while converting the expression from one type to another to avoid the loss of information:
- All integer types to be converted to float.
- All float types to be converted to double.
- All character types to be converted to integer.