Type Conversion Hierarchy in C
In C, when two different data types are used in the same expression, the compiler automatically converts the smaller data type into a larger compatible data type. This process is called Type Conversion or Type Promotion.
The purpose of this conversion is to maintain accuracy and perform calculations correctly when different data types are used together.
Type Conversion Hierarchy
The following order shows how data types are automatically promoted in C:
char → short → int → unsigned int → long → unsigned long → float → double → long double
This means if an expression contains two different data types, the smaller data type is converted into the larger one according to the hierarchy shown above.
Example:
#include <stdio.h>
int main() {
int a = 5;
double b = 2.5;
double result = a + b;
printf("Result = %.1lf", result);
return 0;
}
Output:
Result = 7.5
Explanation:
- The variable a is of type int.
- The variable b is of type double.
- During addition, int is automatically promoted to double.
- This helps perform accurate floating-point calculations.
Another Example:
#include <stdio.h>
int main() {
char ch = 'A'; // ASCII value = 65
int num = 10;
float result = ch + num;
printf("Result = %.1f", result);
return 0;
}
Output:
Result = 75.0
Explanation:
- The character 'A' is automatically converted to its ASCII value 65.
- Then 65 + 10 is calculated.
- The final integer result is converted into float during assignment.
- Final result = 75.0
Summary:
- C automatically converts smaller data types into larger compatible types in expressions.
- This process is called Type Conversion or Type Promotion.
- It helps maintain calculation accuracy between different data types.
- The conversion follows a fixed order called the Type Conversion Hierarchy.
- Example: int → float → double → long double.