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 one. This process is called Type Conversion or Type Promotion.
The purpose of this hierarchy is to avoid data loss during calculations and maintain accuracy in expressions that mix different data types.
Type Conversion Hierarchy
The following order shows how data types are promoted automatically in C++:
bool → char → short → int → unsigned int → long → unsigned long → float → double → long double
This means if an operation involves two data types, the smaller one is converted to the larger one according to the hierarchy shown above.
Example:
#include <iostream>
using namespace std;
int main() {
int a = 5;
double b = 2.5;
double result = a + b; // int is promoted to double
cout << "Result = " << result;
return 0;
}
Output:
Result = 7.5
Explanation:
- The variable a is of type int and b is of type double.
- During addition, int is automatically promoted to double.
- This ensures accurate floating-point calculation and avoids data loss.
Another Example:
#include <iostream>
using namespace std;
int main() {
char ch = 'A'; // ASCII value = 65
int num = 10;
float result = ch + num; // char promoted to int, then to float
cout << "Result = " << result;
return 0;
}
Output:
Result = 75.0
Explanation:
- The character 'A' is first promoted to its ASCII integer value (65).
- Then the integer result is promoted to float during assignment.
- Final result = 65 + 10 = 75.0
Summary:
- C++ automatically promotes smaller data types to larger ones in expressions.
- This prevents loss of data and maintains calculation accuracy.
- The conversion follows a fixed order called Type Conversion Hierarchy.
- Example: int → float → double → long double.