In C++, what type does adding two std::uint16_t sensor readings produce, and why can the result surprise you?
answer
- small types do not stay small
- rank below int
- int if it holds every value
- ~ on a uint8_t gives an int
- storing back truncates modulo 2^16
basics
~20 sThe sum has type int: integral promotion converts any type ranked below int to int when int can hold all its values. 65535 + 1 is therefore 65536, and only storing it back into a std::uint16_t wraps it to 0.
solid answer
~40 sBefore arithmetic, C++ applies **integral promotion**: an operand whose type ranks below `int` — `bool`, `char`, `short`, `unsigned short`, and therefore `std::uint8_t` and `std::uint16_t` on mainstream platforms — becomes `int` if `int` can represent all its values, otherwise `unsigned int`. So `reading + step` with two `std::uint16_t` values is an `int`, and 65535 + 1 is 65536; the wrap to 0 happens only when the result is converted back on assignment. Promotion also explains `~mask == 0xFF` being false for a zero `std::uint8_t`: `~` operates on the promoted `int`, giving -1. And because the promoted type is **signed**, multiplying two large `std::uint16_t` values can overflow `int`, which is undefined behaviour rather than a wrap.
code
cpp · 18 lines#include <cstdint>
#include <iostream>
#include <type_traits>
int main() {
std::uint16_t reading = 65535;
std::uint16_t step = 1;
auto sum = reading + step; // both promoted to int
static_assert(std::is_same_v<decltype(sum), int>);
std::uint16_t stored = reading + step; // converted back: wraps to 0
std::cout << "sum=" << sum << " stored=" << stored << '\n';
std::uint8_t mask = 0;
std::cout << "~mask == 0xFF: " << (~mask == 0xFF)
<< " (~mask is " << ~mask << ")\n";
std::cout << "uint8_t{65} prints as: " << std::uint8_t{65} << '\n';
std::cout << "+uint8_t{65} prints as: " << +std::uint8_t{65} << '\n';
}go deeper
Remember that char, short and the small cstdint types turn into int before any arithmetic happens.
Explain the promotion rule, show where the wrap really happens, and why ~ and printing a uint8_t surprise people.
Spot promotion-driven bugs in bit manipulation and wide multiplications, and fix them with explicit widening rather than casts sprinkled after the fact.
Decide whether code that computes on packed small types must widen explicitly by rule, and which warnings the build enables to keep it honest.
## Small types are promoted before arithmetic C++ does not do arithmetic in types narrower than `int`. Every operand of a built-in arithmetic, bitwise or unary `+`/`-`/`~` operator first goes through **integral promotion**: - A prvalue of an integer type whose **conversion rank** is below `int` — `signed char`, `unsigned char`, `char`, `short`, `unsigned short` — converts to `int` if `int` can represent every value of the source type; otherwise it converts to `unsigned int`. - `bool` promotes to `int` (`false` to 0, `true` to 1). - `char8_t`, `char16_t`, `char32_t` and `wchar_t` promote to the first of `int`, `unsigned int`, `long`, ... that holds all their values. - Bit-fields promote to `int` when `int` can hold all values of the bit-field. On every mainstream platform `int` is 32 bits, so `std::uint8_t` and `std::uint16_t` (aliases of `unsigned char` and `unsigned short` there) promote to **signed** `int`. On a platform with a 16-bit `int`, `std::uint16_t` would promote to `unsigned int` instead — the rule is "the smallest of `int`/`unsigned int` that fits", not "keep the signedness". ## Three consequences in a sensor logger Consider readings stored as `std::uint16_t`: 1. **The intermediate result is wider than the storage.** `auto sum = reading + step;` is an `int`, so with 65535 and 1 it holds 65536. Only `std::uint16_t stored = reading + step;` converts back, and that conversion takes the value modulo 2^16, giving 0. The wrap is real, but it happens on the assignment, not on the `+`. 2. **Bitwise complement sees the promoted value.** With `std::uint8_t mask = 0;`, `~mask` is the `int` -1 (all 32 bits set), not 255, so `~mask == 0xFF` is false. Write `static_cast<std::uint8_t>(~mask) == 0xFF`, or compare against a value of the same width. 3. **Signed overflow can appear in unsigned code.** `std::uint16_t a = 65535, b = 65535; a * b` multiplies two `int` values whose product exceeds `INT_MAX`. The lesson on undefined behaviour covers what that means; the fix here is to convert one operand to a wide unsigned type first: `std::uint32_t{a} * b`. ## Printing and comparisons Promotion also explains output surprises. `std::uint8_t` is `unsigned char` on mainstream platforms, so `std::cout << std::uint8_t{65}` selects the character overload and prints `A`; `std::cout << +std::uint8_t{65}` applies unary `+`, promotes to `int`, and prints `65`. Similarly, comparing a `char` with `0xE9` compares two `int`s after promotion, and the answer depends on whether plain `char` is signed on the platform. | Expression (operands `std::uint8_t` or `std::uint16_t`) | Type after promotion | Note | |---|---|---| | `reading + step` | `int` | no wrap at 65535 | | `~mask` | `int` | -1 for `mask == 0` | | `a * b` | `int` | may exceed `INT_MAX` | | `+byte` | `int` | prints as a number | | `reading += step` | `std::uint16_t` | computed in `int`, converted back | ## Why the language does this C's model, inherited by C++, computes in the machine's natural word size and narrows only on storage. That keeps small-type arithmetic cheap on most hardware, but it means the declared type of a variable says nothing about the type of an expression built from it. It also affects overload resolution and templates. A call `record(reading + step)` with overloads for `std::uint16_t` and `int` picks the `int` one, and `std::max(reading, reading + 1)` fails to deduce a single template argument because one argument is `std::uint16_t` and the other `int`. When a function template or `auto` captures the type of such an expression, it captures the promoted type. When the exact type matters, inspect it: `static_assert(std::is_same_v<decltype(reading + step), int>)` documents the promotion and fails if a future refactor changes it. ## What to do in code review - Treat `decltype` of a small-type expression as `int` unless proven otherwise. - Convert explicitly to the width you want before multiplying or shifting small unsigned values. - Cast back with `static_cast` when you intend the truncation, so the reader sees it. - Compile with `-Wconversion` in GCC or Clang to see narrowing assignments, knowing it will not report every case.
- Why can multiplying two std::uint16_t values be undefined behaviour even though both are unsigned?Both operands promote to signed `int` when `int` is 32 bits, so the multiplication is an `int` multiplication. 65535 * 65535 exceeds `INT_MAX`, and signed overflow is undefined behaviour. Converting one operand to `std::uint32_t` first makes the multiplication unsigned and well defined.
- Does promotion happen for a compound assignment like reading += step?Yes. `reading += step` behaves like `reading = reading + step` with `reading` evaluated once: the addition happens in the promoted `int` and the result converts back to `std::uint16_t`, wrapping modulo 2^16. The narrowing is implicit, which is why it rarely draws a warning.
- adding two std::uint16_t values gives a std::uint16_t
- unsigned operands can never cause signed overflow
- ~ on a zero uint8_t gives 255
- small types keep their signedness when promoted
- std::uint8_t always prints as a number with std::cout