C++ automatic type promotion
Date: 2023-02-22Last modified: 2024-11-02
Table of contents
Introduction
As mentioned at [C++ numerical
☢
Warning
Integral types less than 4 bytes in size don’t support arithmetic operations.
-
char
: 1 byte -
short int
: 2 bytes
⚡
Tip
The type of a floating literal is double
unless explicitly
specified by a suffix. The suffixes f
and F
specify float
,
the suffixes l
and L
specify long double
.
#define print_type(var) \
fmt::print("{} = {} is {} \n", #var, var, typeid(var).name());
int main([[maybe_unused]] int argc, [[maybe_unused]] char **argv) {
int a = 10;
int b = 20;
auto max1 = (a > b) ? a : b; // max1 is i
auto max2 = (a > b) ? 10.0f : b; // max2 is f
auto max3 = (a > b) ? a : 20.0f; // max3 is f
auto max4 = (a > b) ? 10.0 : b; // max4 is d
auto max5 = (a > b) ? a : 20.0; // max5 is d
short int x = 10;
short int y = 20;
short int z = 0;
auto max6 = (x > y) ? x : y; // max6 is s
// 🔴 Implicit conversion to int
// short int don't support arithmetic
auto max7 = (x > y) ? x + z : y + z; // max7 is i
print_type(max1);
print_type(max2);
print_type(max3);
print_type(max4);
print_type(max5);
print_type(max6);
print_type(max7);
return 0;
}
Possible output
max1 = 20 is i
max2 = 20 is f
max3 = 20 is f
max4 = 20 is d
max5 = 20 is d
max6 = 20 is s
max7 = 20 is i