As a C++ lead, would you standardise on signed or unsigned integers for sizes and indices, and where do fixed-width types belong in your APIs?
answer
- the standard library already chose
- wrap is defined, overflow is not
- where do conversions happen
- std::ssize and std::cmp_less
- fixed widths at the boundary
basics
~20 sEither can work: containers use unsigned std::size_t, while signed indices make subtraction safe and overflow detectable. Pick one rule, convert at named boundaries with checks, enforce it with warnings, and keep fixed-width types for layouts that leave the process.
solid answer
~50 sI would decide by where the conversions land. Standard containers, `std::span` and `sizeof` all speak `std::size_t`, so an unsigned policy needs no casts at library calls but makes every subtraction and reverse loop a wrap hazard, and wraps are invisible to `-fsanitize=undefined`. A signed policy (`std::ptrdiff_t` or `int` for counts and indices, C++20 `std::ssize` at container boundaries) makes differences and loops natural and lets UBSan catch overflow, at the cost of conversions at every library call. Either works if the team names the boundary, converts there with a check (`std::in_range`, `std::cmp_less`), and turns `-Wsign-compare` — and ideally `-Wsign-conversion` — into errors. Unsigned stays for bit masks, hashes and raw bytes. Fixed-width types belong where layout crosses a boundary — wire formats, files, shared memory, ABI-stable structs — not in every local variable; and `long` never appears in a portable interface.
go deeper
Know that standard containers return an unsigned size_t and that mixing it with int needs care.
Explain what goes wrong with unsigned subtraction and reverse loops, and which C++20 helpers bridge signed and unsigned code.
Show how you would enforce one signedness rule with warnings, checked conversions and sanitizers in a mixed codebase.
Argue the tradeoff for this codebase's shape, write the rule and its boundaries down, and plan a staged rollout of the warnings.
## Why this is a decision and not a fact C++ gives you two defensible models, and the standard library has already picked one of them for its own interfaces. `size()` on every container returns an unsigned `size_type` (`std::size_t` for `std::vector`), `std::span` uses `std::size_t`, and `sizeof` yields `std::size_t`. Meanwhile, pointer differences and iterator distances are signed (`std::ptrdiff_t`). Any codebase therefore mixes both, and the real question is **where the conversions happen and who checks them**. ## The two camps | | Unsigned sizes (`std::size_t`) | Signed sizes (`std::ptrdiff_t`, `int`) | |---|---|---| | Matches the standard library | yes, no casts at container calls | needs `std::ssize` or casts at calls | | `a - b` when `b > a` | wraps to a huge value, silently | negative, as arithmetic expects | | Reverse loop `i >= 0` | never terminates | works | | Overflow | defined wrap, invisible to `-fsanitize=undefined` | undefined behaviour, reported by `-fsanitize=signed-integer-overflow` | | Range | full width for very large buffers | half the range, rarely a real limit | Arguments people bring to the meeting: - **For unsigned**: "a size can't be negative", zero friction with the library, a full 64-bit range, and modular arithmetic that is defined. - **For signed**: a negative intermediate is an honest value rather than a silent wrap, differences and loops read naturally, and tools can detect overflow because it is undefined behaviour. - **The tie-breaker** is usually the code's shape: parsing, geometry and anything with offsets and differences favours signed; code that is mostly calls into containers favours unsigned. ## Making either rule safe The failure mode is not choosing wrong; it is mixing silently. A workable rule has three parts: 1. **Name the boundary.** Untrusted input, file formats and container calls are where conversions happen, and only there. 2. **Convert with a check.** C++20 gives `std::in_range<T>(v)` to test that a value fits before converting, the `std::cmp_less` family in `<utility>` to compare across signedness, and `std::ssize` to get a signed size from a container. 3. **Let the compiler enforce it.** `-Wsign-compare` (in GCC's `-Wall` for C++ and Clang's `-Wextra`) as an error is cheap; `-Wsign-conversion` catches more and costs more churn, so it is often enabled per directory, starting with parsing code. Unsigned keeps its place where the arithmetic really is modular or bitwise: masks, flags, hash mixing, checksums, raw bytes (`unsigned char`, `std::byte`). ## Where fixed-width types belong `<cstdint>` types state a width, which is exactly what a boundary needs and rarely what a loop counter needs. - **Use exact widths** (`std::uint32_t`, `std::int64_t`) for wire formats, file headers, shared memory, GPU buffers, hardware registers and ABI-stable structs — anywhere bytes leave the process. - **Use `int`, `std::size_t` or `std::ptrdiff_t`** for in-memory counts and indices; forcing `std::int32_t` there adds conversions without adding meaning. - **Never use `long` in a portable interface.** It is 64 bits on LP64 Linux and macOS and 32 bits on 64-bit Windows, so a struct containing it changes layout between platforms. - Remember that `std::uint8_t` and `std::uint16_t` promote to `int` in arithmetic; a fixed width on storage says nothing about the width of the expression. ## Rolling the rule out - Write the rule down with the reasons, because "sizes can't be negative" will be re-argued in every review otherwise. - Introduce warnings as errors per module, starting where untrusted data is parsed. - Run sanitizers in CI with the rule in mind: `-fsanitize=undefined` for signed code; Clang's opt-in `-fsanitize=unsigned-integer-overflow` for unsigned-heavy parsing code, with an allowlist for intentional wraps. - Revisit the decision when the code's shape changes — a library-heavy service can live comfortably with unsigned sizes that a geometry engine would fight every day. ## A sample rule a team can adopt One concrete wording that has the properties above: "Counts, indices and differences are `std::ptrdiff_t`; container sizes are read with `std::ssize`; untrusted input is validated with `std::in_range` before any conversion; unsigned types are reserved for bit patterns, hashes and byte buffers; serialized structs use exact-width types only; `-Wsign-compare` is an error everywhere and `-Wsign-conversion` in the parsers." The mirror-image rule with `std::size_t` is equally valid. What matters is that the rule is short enough to remember, checkable by the compiler, and explicit about the few places where the two worlds meet.
- If you choose signed indices, how do you call standard containers without casts everywhere?Use C++20 `std::ssize(c)` to obtain a signed size, keep indices as `std::ptrdiff_t`, and convert once when indexing with a checked helper or `static_cast<std::size_t>` after asserting non-negativity. Range-based `for` and algorithms avoid indices entirely for most loops, which shrinks the number of conversion sites to a handful the warnings can police.
- Why should a serialized struct avoid int_fast32_t and long even though both are at least 32 bits?Both are implementation-chosen widths: `long` is 64 bits on LP64 and 32 on 64-bit Windows, and the fast types vary between C libraries. A struct written by one build and read by another then disagrees about field offsets. Exact-width types such as `std::int32_t` make the layout a property of the source code, not of the platform.
- sizes can never be negative, so unsigned is always the correct type
- signed indices are always slower than unsigned ones
- std::int32_t should replace int everywhere for portability
- unsigned overflow is caught by UBSan like signed overflow
- the choice does not matter once the code compiles without warnings
Assumes C++20 or later for std::ssize, std::in_range and the std::cmp_less family; container size_type has been unsigned in every standard.