CKTIS / C++
Integer promotions
Work out the type used for arithmetic on `std::uint8_t` and `std::uint16_t`, and distinguish it from the destination type and from how a value is printed.
Version: ISO C++23; implementation support may vary
Syntax
a + b // built-in addition: promote operands, then find a common type
static_cast<std::uint8_t>(a + b) // convert the result, not the operands
std::cout << static_cast<unsigned int>(byte) // numeric outputIn C++23, built-in integer addition uses the usual arithmetic conversions: it applies integer promotions (called integral promotions in the standard) before choosing a common operand type. An ordinary unsigned integer type ranked below int promotes to int if int can represent its entire range, and to unsigned int otherwise. The <cstdint> aliases std::uint8_t and std::uint16_t are optional. Where provided, std::uint8_t promotes to int; std::uint16_t promotes to int if int can represent 65535. Otherwise the std::uint16_t operand is unsigned int after promotions: either it promotes to that type or it already has that type.
If a and b are std::uint8_t values 250 and 10, a + b is an int with value 260. Only the later conversion static_cast<std::uint8_t>(a + b) produces 4, which is 260 modulo 256. The destination type does not change how the sum is computed.
If std::uint8_t aliases unsigned char, std::cout << byte selects a character overload rather than a numeric one. Use std::cout << static_cast<unsigned int>(byte) to print its numeric value.
In a + 1u, a still promotes to int. The literal 1u has type unsigned int, so the usual arithmetic conversions choose unsigned int as the common type.
Examples
#include <cstdint>
#include <iostream>
#include <limits>
#include <type_traits>
int main() {
constexpr std::uint8_t a = 0xFAu, b = 10;
constexpr auto sum = a + b;
constexpr auto byte = static_cast<std::uint8_t>(sum);
static_assert(std::is_same_v<decltype(a + b), int>);
static_assert(sum == 260 && byte == 4);
constexpr std::uint16_t x = 1000, y = 24;
using Sum16 = std::conditional_t<(std::numeric_limits<int>::digits >= 16),
int, unsigned int>;
static_assert(std::is_same_v<decltype(x + y), Sum16>);
const unsigned char letter = 'A';
std::cout << sum << '\n'
<< static_cast<unsigned int>(byte) << '\n'
<< x + y << '\n'
<< letter << '\n';
}Result
260 4 1024 A
The expected lines show the sum `260`, the converted value `4` printed numerically, the sum `1024` of the 16-bit operands, and `A` printed by the `unsigned char` overload.
Related lessons
- C++ · Lesson 17 · Advanced · Version: 3
Sources
- Integral promotions [conv.prom]
- Conversion ranks [conv.rank]
- Usual arithmetic conversions [expr.arith.conv]
- Integral conversions [conv.integral]
- Integer literals [lex.icon]
- Fundamental types [basic.fundamental]
- Header <cstdint> synopsis [cstdint.syn]
- Working Draft, Standard for Programming Language C++ (N4950), including character inserters [ostream.inserters.character]