skip to content

Arithmetic Types

int, char, bool and the floating types have minimum sizes, not fixed ones, and mixing signed with unsigned converts silently. Interviewers ask what a comparison really compares.

on this pageshow

explore

questions

6

What does the C++ standard guarantee about the widths of int and long and the signedness of plain char?

level: juniorimportance: must knowfreq 70%

answer

  1. minimum, never exact
  2. a minimum-width table per type
  3. sizeof(char) is 1, CHAR_BIT at least 8
  4. 64-bit Windows keeps long at 32
  5. char: a third, distinct type

basics

~20 s

C++ fixes only minimum widths: short and int at least 16 bits, long 32, long long 64, and sizeof(char) is 1. Whether plain char is signed is implementation-defined, so exact-width code uses std::int32_t and its <cstdint> siblings.

solid answer

~40 s

The standard gives a table of **minimum** widths, not sizes: `signed char` at least 8 bits, `short` and `int` at least 16, `long` at least 32, `long long` at least 64, and each type provides at least as much storage as the one before it. `sizeof(char)` is 1 by definition, and a byte is `CHAR_BIT` bits, at least 8. Platforms then differ: `long` is 64 bits on 64-bit Linux and macOS (LP64) but 32 bits on 64-bit Windows (LLP64). Plain `char` is a distinct type whose representation matches either `signed char` or `unsigned char`, and the implementation chooses which — x86-64 makes it signed, AArch64 Linux unsigned. When a width matters, use `<cstdint>`: `std::int32_t` is exact but optional, while `std::int_least32_t` always exists. Since C++20, signed integers are also guaranteed to be two's complement.

code

cpp · 17 lines
cpp
#include <climits>
#include <cstdint>
#include <iostream>
#include <type_traits>

// Fail the build, not the field device, when an assumption breaks.
static_assert(CHAR_BIT == 8, "the log format assumes 8-bit bytes");
static_assert(sizeof(std::int32_t) == 4);

int main() {
    std::cout << "int:       " << sizeof(int) * CHAR_BIT << " bits\n";
    std::cout << "long:      " << sizeof(long) * CHAR_BIT << " bits\n";
    std::cout << "long long: " << sizeof(long long) * CHAR_BIT << " bits\n";
    std::cout << "char is signed: " << std::is_signed_v<char> << '\n';
    char c = '\xE9';
    std::cout << "'\\xE9' read as int: " << int{c} << '\n';
}

go deeper

for a junior

Recall the minimum-width table, that sizeof(char) is always 1, and that plain char may be signed or unsigned depending on the platform.

for a middle

Explain the LP64 and LLP64 data models, why long is the portability trap, and how the exact, least and fast families in cstdint differ.

for a senior

Show how you would make width and signedness assumptions explicit with static_assert and cstdint types in a codebase that ships to several architectures.

for a principal

Weigh exact-width types at serialization and ABI boundaries against plain int in internal code, and decide which assumptions the build must check per target.

## Minimum widths, not sizes C++ never says "`int` is 32 bits". The standard's **minimum-width table**, in its section on fundamental types, promises only lower bounds on the number of value bits: | Type | Minimum width | |---|---| | `signed char` | 8 bits | | `short` | 16 bits | | `int` | 16 bits | | `long` | 32 bits | | `long long` | 64 bits | Three more rules complete the picture: - In the list `signed char`, `short`, `int`, `long`, `long long`, each type provides **at least as much storage** as those before it, so `long` is never smaller than `int`. - Every unsigned type has the same width as its signed partner, and unsigned arithmetic is performed **modulo 2^N**. - `sizeof(char)` is **1 by definition**. A byte is `CHAR_BIT` bits (from `<climits>`), which is at least 8; some digital signal processors use 16- or 32-bit bytes, and on them `sizeof(int)` can legitimately be 1. Everything beyond the table is **implementation-defined**: the compiler documents its choice, and the choice follows the platform's ABI. ## The data models you meet in practice The widths a compiler picks are usually summarised as a **data model**: | Model | `int` | `long` | `long long` | pointer | Typical platforms | |---|---|---|---|---|---| | ILP32 | 32 | 32 | 64 | 32 | 32-bit x86 and ARM | | LP64 | 32 | 64 | 64 | 64 | 64-bit Linux, macOS and most Unix systems | | LLP64 | 32 | 32 | 64 | 64 | 64-bit Windows | The integer type that moves is `long`. Code that keeps a pointer, a file offset or a 64-bit counter in `long` works on Linux and macOS and silently truncates on Windows. Interviewers like this because "it's 64-bit, so `long` is 64 bits" sounds right and is wrong on one of the three biggest desktop platforms. ## Plain char is a third type `char`, `signed char` and `unsigned char` are **three distinct types**. Plain `char` has the representation and range of one of the other two, and which one is implementation-defined. Clang's own target defaults show the split: - **signed** on x86 and x86-64 (Linux and Windows) and on arm64 macOS; - **unsigned** on 32-bit ARM Linux, AArch64 Linux, 64-bit PowerPC Linux and RISC-V Linux; - switchable with `-fsigned-char` and `-funsigned-char` in both GCC and Clang. The consequence is portability bugs with bytes above `0x7F`: `char c = '\xE9';` reads back as -23 on x86-64 and as 233 on AArch64 Linux, so a range check like `c >= 0x80` or using `c` as a table index behaves differently per platform. Raw bytes belong in `unsigned char` or `std::byte` (C++17); text belongs in `char`. Because the three types are distinct, `f(char)` and `f(signed char)` are separate overloads even where their ranges match. ## Fixed-width types in `<cstdint>` `<cstdint>` gives names that state intent: | Family | Example | Promise | Always provided? | |---|---|---|---| | exact width | `std::int32_t`, `std::uint16_t` | exactly N bits | no, optional | | least width | `std::int_least32_t` | smallest type with at least N bits | yes | | fast | `std::int_fast32_t` | the type the implementation considers fastest with at least N bits | yes | 1. Use the **exact-width** types for wire formats, file headers, register maps and anything serialised. They are optional only because an exotic platform may have no matching type; there the code fails to compile instead of misbehaving. 2. Use `least` types when you need a range but not an exact layout. 3. Keep `fast` types out of structs that cross a process or file boundary: each C library chooses their sizes (`std::int_fast16_t` is 2 bytes on arm64 macOS), so two builds can disagree about a layout. ## What C++20 pinned down Before C++20, a signed integer could in principle use ones' complement or sign-magnitude, and converting an out-of-range value to a signed type gave an implementation-defined result. C++20 requires **two's complement** representation and defines every integral conversion as the value congruent modulo 2^N, so `static_cast<std::int8_t>(200)` is -56 everywhere. Signed **overflow** in arithmetic is still undefined behaviour; that belongs to the material on undefined behaviour, not to the type sizes. ## State assumptions where the compiler checks them Instead of trusting folklore, write the assumption down: `static_assert(CHAR_BIT == 8)`, `static_assert(sizeof(long) >= 8)`, `std::numeric_limits<int>::digits` (31 for a 32-bit `int`) and `std::is_signed_v<char>`. A failed assertion on a new target costs a minute; a truncated sensor reading in the field costs a release.

  • Why is std::int32_t optional while std::int_least32_t is always provided?
    An exact-width alias needs a type with exactly that many bits, and a platform with 9-bit bytes or 36-bit words may have none. The `least` and `fast` families only promise at least N bits, which any conforming implementation can supply. Every mainstream target provides the exact-width types, so the practical effect is that code needing them fails to compile on an exotic target instead of silently using the wrong width.
  • Is sizeof(long) == 8 on every 64-bit platform?
    No. 64-bit Linux and macOS use the LP64 model, where `long` and pointers are 64 bits, but 64-bit Windows uses LLP64, where `long` stays 32 bits and only `long long` and pointers are 64. Code that stores a pointer or a file offset in `long` truncates when ported to Windows; `std::intptr_t`, `std::int64_t` or `std::ptrdiff_t` say what they mean.
  • Are char, signed char and unsigned char interchangeable when you overload a function?
    No. They are three distinct types even though plain `char` shares its representation with one of the other two, so `f(char)`, `f(signed char)` and `f(unsigned char)` are three separate overloads. A call with a `char` argument picks the `char` overload exactly; it does not matter whether the platform makes `char` signed.

  • int is always 32 bits because every compiler I use makes it so
  • long is 64 bits on every 64-bit platform
  • plain char is just another name for signed char
  • sizeof(char) is 1 only on machines with 8-bit bytes
  • std::int_fast32_t is exactly 32 bits, so it is safe in a file format
  • signed integers may still be ones' complement in C++20

Assumes C++20 or later: two's complement representation and modular integral conversion are guaranteed since C++20 and unchanged in C++23.

open as a page

Why does the C++ comparison -1 < 1u evaluate to false, and which rule picks the common type?

level: middleimportance: must knowfreq 70%

basics

~20 s

The usual arithmetic conversions convert both operands to one common type. int and unsigned int share a rank, so the int converts to unsigned and -1 becomes UINT_MAX (4294967295 for 32 bits), not less than 1.

open as a page

Why does a C++ float holding 0.1f compare unequal to the literal 0.1, and how should floating values be compared?

level: middleimportance: should knowfreq 45%

basics

~20 s

The literal 0.1 is a double, so the float is converted to double before ==. 0.1f widened is 0.10000000149011612, not the double nearest 0.1, so they differ. Compare floats against float literals, and compare computed values with a tolerance.

open as a page

In C++, what type does adding two std::uint16_t sensor readings produce, and why can the result surprise you?

level: middleimportance: should knowfreq 50%

basics

~20 s

The 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.

open as a page

A C++ sensor logger validates network input with len <= buf.size() - offset, where offset and len are int; why do hostile packets pass, and how do you fix it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

buf.size() returns std::size_t, so the int offset converts to unsigned and the subtraction wraps: an offset past the end or a negative one makes buf.size() - offset exceed the buffer, so bad lengths pass. Reject negatives first, then compare in one signedness.

open as a page

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?

level: principalimportance: should knowfreq 30%

basics

~20 s

Either 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.

open as a page