# Integer arithmetic and overflow

> Unsigned integers wrap around, signed integers do not get to overflow at all, and promotion quietly turns narrow unsigned arithmetic into signed arithmetic. This topic covers the division rules, safe comparison, narrowing, and the newer saturating and checked operations.

- **Source:** C++ Atlas (https://cppatlas.com/topics/integer-arithmetic-and-overflow)
- **Track:** Library utilities
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [expr.pre] (https://eel.is/c++draft/expr.pre), [expr.mul] (https://eel.is/c++draft/expr.mul), [expr.const] (https://eel.is/c++draft/expr.const), [basic.fundamental] (https://eel.is/c++draft/basic.fundamental), [conv.integral] (https://eel.is/c++draft/conv.integral), [dcl.init.list] (https://eel.is/c++draft/dcl.init.list), [utility.intcmp] (https://eel.is/c++draft/utility.intcmp), [c.math.abs] (https://eel.is/c++draft/c.math.abs), [iterator.range] (https://eel.is/c++draft/iterator.range)
- **cppreference links:** [Arithmetic operators](https://en.cppreference.com/w/cpp/language/operator_arithmetic), [Integer comparison functions (cmp_less, in_range)](https://en.cppreference.com/w/cpp/utility/intcmp), [std::in_range](https://en.cppreference.com/w/cpp/utility/in_range), [Implicit conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion), [Usual arithmetic conversions](https://en.cppreference.com/w/cpp/language/usual_arithmetic_conversions), [Saturation arithmetic](https://en.cppreference.com/w/cpp/numeric/add_sat), [Undefined behavior](https://en.cppreference.com/w/cpp/language/ub), [Fixed width integer types](https://en.cppreference.com/w/cpp/types/integer)
- **Prerequisites:** fundamental-types-and-arithmetic-conversions, implicit-conversions, constant-expressions

## The one idea

C++ has two integer worlds with opposite contracts. Unsigned arithmetic is arithmetic modulo a power of two, so overflow is a defined, wrapping result. Signed arithmetic has no such result: if the mathematical value does not fit, the behaviour of the expression is undefined. The language does not wrap signed values even though C++20 requires two's complement representation.

> **Mental model.** An unsigned operation always has an answer, and that answer is reduced modulo 2 to the width. A signed operation has an answer only when the true result fits. When it does not, the program has left the rules, and the optimizer is allowed to have assumed that it never would.

The practical consequence is that a rule you learned for `unsigned` is a bug when you apply it to `int`, and the reverse. The part that surprises experienced programmers is how often an expression that looks unsigned is really signed, because of promotion.

## Signed overflow is undefined, and the compiler uses that

[expr.pre] says that if evaluating an expression produces a result that is not in the range of representable values for its type, the behaviour is undefined. For signed integers this is not a theoretical remark. Compilers use it to reason that `x + 1 > x` is always true.

```cpp
bool f(int x)      { return x + 1 > x; }  // GCC at -O2 on arm64 compiles this to "return true"
bool g(unsigned x) { return x + 1 > x; }  // false when x is UINT_MAX, and the code must handle it
```

You can ask the toolchain for help: `-fsanitize=signed-integer-overflow` reports the problem at run time, `-ftrapv` turns it into a trap, and `-fwrapv` gives it a wrapping meaning as a non-standard extension. Constant evaluation is the standard's own detector. A `constexpr` initializer whose evaluation overflows is not a constant expression, so the compiler must reject it.

```cpp
#include <climits>

// constexpr int a = INT_MAX + 1;   // ill-formed: signed overflow is not a constant expression
constexpr unsigned b = UINT_MAX + 1u;  // OK: unsigned arithmetic wraps, b is 0
static_assert(b == 0);
```

The consequence for checks is that you must test before the operation, never after it. Writing `if (a + b < a)` to detect overflow of a signed `a + b` is itself undefined when it overflows, and the optimizer is free to delete the test because it may assume the sum never wraps. The portable form compares against the limits first.

```cpp
#include <climits>

bool add_overflows(int a, int b) {
  return (b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b);
}
// Wrong: return a + b < a;   // evaluates the overflowing addition, then tests it
```

For unsigned values the after-the-fact test is fine, because wrapping is defined: `a + b < a` is true exactly when the unsigned sum wrapped. That asymmetry is another reason to keep sizes and bit patterns unsigned and to keep quantities that can go negative signed.

## Promotion turns unsigned into signed

Operands narrower than `int` are promoted before arithmetic. On a platform with 32-bit `int`, an `unsigned short` becomes an `int`, so multiplying two of them is a signed multiplication that can overflow. The rules for promotion and the usual arithmetic conversions are in `fundamental-types-and-arithmetic-conversions`. Here the consequence matters.

```cpp
constexpr unsigned short a = 65535;
// constexpr auto r = a * a;
// ill-formed with 32-bit int: both promote to int, and 4294836225 does not fit
constexpr auto ok = static_cast<unsigned>(a) * a;  // OK: 4294836225u, unsigned arithmetic
```

The type of `r` would be `int`, not `unsigned short` or `unsigned`. The same trap catches `uint8_t` and `uint16_t` arithmetic in hash functions and checksums. The fix is to convert one operand to `unsigned` before the operation. Writing `1u * a * b` does the same.

## Division and remainder

Division truncates toward zero. This has been required since C++11, where earlier standards left it to the implementation for negative operands. The remainder has the sign of the dividend, and the identity `(a / b) * b + a % b == a` always holds when the quotient is representable.

```cpp
#include <cstdio>

int main() {
  std::printf("%d %d\n", -7 / 2, -7 % 2);   // -3 -1
  std::printf("%d %d\n", 7 / -2, 7 % -2);   // -3 1
}
```

Dividing by zero is undefined for both `/` and `%`. The other case is `INT_MIN / -1`, whose mathematical result 2147483648 does not fit in a 32-bit `int`. [expr.mul] says that when the quotient is not representable, the behaviour of both `a / b` and `a % b` is undefined. So `INT_MIN % -1` is undefined as well, although its mathematical value would be 0. On x86 the hardware traps on it.

> **Standardese.** [expr.mul] states that for integral operands, if the quotient `a / b` is representable in the type of the result, then `(a / b) * b + a % b` equals `a`; otherwise the behaviour of both `a / b` and `a % b` is undefined. This is why the remainder operator shares the hazard of the division.

`std::abs(INT_MIN)` fails the same way: the absolute value is not representable, and [c.math.abs] leaves it undefined. If you need the absolute value of an arbitrary `int`, compute in a wider type or convert to `unsigned` first.

## Comparing mixed signs safely

When a signed and an unsigned operand of the same rank meet, the signed one is converted to unsigned. So `-1 < 1u` is false, because `-1` becomes `UINT_MAX`. The surprise disappears when the unsigned type is narrower: `-1 < static_cast<unsigned short>(1)` is true, because both promote to `int`.

C++20 added comparison functions in `<utility>` that compare by mathematical value. They are `std::cmp_equal`, `cmp_not_equal`, `cmp_less`, `cmp_greater`, `cmp_less_equal` and `cmp_greater_equal`. Next to them is `std::in_range<R>(value)`, which tells you whether a value fits in type `R`.

```cpp
#include <cstdint>
#include <cstdio>
#include <utility>

int main() {
  std::printf("%d %d\n", -1 < 1u, std::cmp_less(-1, 1u));  // 0 1
  std::printf("%d %d\n", std::in_range<unsigned>(-1),
                         std::in_range<std::uint8_t>(255)); // 0 1
}
```

These functions accept only standard and extended integer types. `char`, `bool`, `char8_t`, `char16_t`, `char32_t` and `wchar_t` are rejected at compile time, so `std::cmp_less('a', 1)` is ill-formed. The functions are meant for numbers only.

C++20 also added `std::ssize(c)`, which returns a signed size, so loops over indices need no cast. Together with the previous point, this is the standard cure for the classic loop bug.

```cpp
#include <vector>

void bad(const std::vector<int>& v) {
  // for (std::size_t i = v.size() - 1; i >= 0; --i)  // i >= 0 is always true; v.size() - 1 wraps if empty
}

void good(const std::vector<int>& v) {
  for (auto i = std::ssize(v) - 1; i >= 0; --i) { (void)v[i]; }
  for (auto i = v.size(); i-- > 0; ) { (void)v[i]; }  // unsigned idiom, correct for empty vectors
}
```

> **Pitfall.** An empty vector has `size()` equal to zero, and `size() - 1` is `SIZE_MAX`, a well-defined wrap that is almost never what you meant. The condition `i >= 0` on an unsigned `i` is always true, so the first loop above never ends on its own.

## Narrowing and conversion

Converting any integer to an unsigned type is always modular. Converting to a signed type, when the value does not fit, was implementation-defined until C++20, and since C++20 it is modular too: the result is the unique value congruent to the source modulo 2 to the width. So an `int` holding 200 converts to `std::int8_t` as -56 in every C++20 program.

```cpp
#include <cstdint>

void narrow(int big) {
  std::int8_t a = big;      // if big is 200: -56 since C++20, implementation-defined before
  unsigned u = -1;          // UINT_MAX, always
  // std::int8_t b{big};    // ill-formed: narrowing in list-initialization
  std::int8_t c{100};       // OK: a constant that fits is not narrowing
  (void)a; (void)u; (void)c;
}
```

List-initialization is stricter. A conversion that may change the value is ill-formed unless the source is a constant expression whose value fits. Defined does not mean harmless: a modular conversion still silently changes the number.

## Saturating and checked arithmetic

Two library features give you overflow handling without undefined behaviour. Both are C++26.

Saturating arithmetic in `<numeric>` clamps to the limits of the type. The C++26 draft names the functions `std::add_sat`, `std::sub_sat`, `std::mul_sat` and `std::div_sat`, plus `std::saturate_cast<R>(x)`. These are C++26 additions. The libstdc++ 16 headers used for this topic spell the same operations `saturating_add`, `saturating_sub`, `saturating_mul`, `saturating_div` and `saturating_cast`, so check your library before relying on the draft names.

```cpp
// C++26: std::add_sat(std::int8_t{100}, std::int8_t{100}) == 127
// C++26: std::saturate_cast<std::uint8_t>(-5) == 0
```

Checked arithmetic comes from the C23 header `<stdckdint.h>`, which C++26 adopts. The functions `ckd_add`, `ckd_sub` and `ckd_mul` take a pointer to the result and two integer operands. They return `true` if the result did not fit, and in that case they store the wrapped value.

```cpp
#include <stdckdint.h>  // C++26

int r;
bool overflowed = ckd_add(&r, 2147483647, 1);  // true, and r holds the wrapped result
```

Until your toolchain has them, the compiler builtins `__builtin_add_overflow` and its relatives do the same job in GCC and Clang.

## What to remember

- Unsigned overflow wraps modulo 2 to the width; signed overflow is undefined, and compilers optimize on that.
- Constant evaluation rejects signed overflow, which makes `constexpr` a good test for it.
- `unsigned short * unsigned short` is a signed `int` multiplication; convert an operand to `unsigned` first.
- Division truncates toward zero since C++11, and the remainder takes the sign of the dividend.
- `INT_MIN / -1` and `INT_MIN % -1` are both undefined, as is division by zero and `std::abs(INT_MIN)`.
- `-1 < 1u` is false; use `std::cmp_less` and friends, or `std::in_range`, to compare by value.
- The `cmp_*` functions reject `char` types and `bool`.
- Use `std::ssize` or the `i-- > 0` idiom to avoid `size_t` underflow in loops.
- Narrowing to a signed type is modular since C++20, but list-initialization still forbids narrowing.
- C++26 adds saturating operations in `<numeric>` and checked `ckd_*` operations in `<stdckdint.h>`.

## Concept Map Outline

- **Integer arithmetic and overflow:** Unsigned wraps by definition; signed overflow is undefined; promotion hides which one you are doing.
  - **Overflow contracts:** Unsigned arithmetic is modular; signed overflow leaves the language rules.
    - **Unsigned wraparound:** Results are reduced modulo 2 to the width, so UINT_MAX + 1u is 0.
    - **Signed overflow:** Undefined behavior under [expr.pre]; compilers may assume it never happens.
    - **Two's complement, C++20:** The representation is now fixed, but signed overflow is still undefined.
    - **Constant evaluation:** Overflow in a constexpr initializer is not a constant expression, so it is diagnosed.
  - **Promotion trap:** Narrow unsigned operands become int before arithmetic.
    - **unsigned short product:** Both operands promote to int, so 65535 * 65535 overflows with a 32-bit int.
    - **The fix:** Cast an operand to unsigned first, or write 1u * a * b.
  - **Division and remainder:** Quotients truncate toward zero and the remainder follows the dividend.
    - **Truncation, C++11:** -7 / 2 is -3 and -7 % 2 is -1; (a / b) * b + a % b equals a.
    - **INT_MIN / -1:** The quotient does not fit, so both division and remainder are undefined.
    - **Division by zero:** Undefined for both / and %.
    - **abs(INT_MIN):** The result is not representable, so the behavior is undefined.
  - **Comparing integers:** Mixed-sign comparison converts to unsigned; C++20 adds value-based helpers.
    - **-1 < 1u is false:** The signed operand converts to unsigned, so -1 becomes UINT_MAX.
    - **cmp_less family:** std::cmp_* compare mathematical values; they reject char types and bool.
    - **in_range:** std::in_range<R>(v) tells whether v fits in type R without converting it.
    - **ssize and loops:** Use std::ssize or i-- > 0 to avoid size_t underflow in reverse loops.
  - **Conversions:** Conversion to unsigned is modular; to signed it is modular since C++20.
    - **Narrowing to signed:** 200 to int8_t is -56 in C++20; it was implementation-defined before.
    - **List-initialization:** Narrowing is ill-formed unless the source is a constant that fits.
  - **Safe arithmetic, C++26:** Library tools that handle overflow without undefined behavior.
    - **Saturating operations:** C++26 clamps to the type's limits; libstdc++ 16 spells them saturating_add and so on.
    - **ckd_add and ckd_mul:** From <stdckdint.h>: return true on overflow and store the wrapped result.
    - **Compiler builtins:** __builtin_add_overflow does the same job in GCC and Clang today.

## Standardese Quiz Questions

### Question 1 [warmup] ([utility.intcmp], [expr.rel])

In C++20 or later, what is printed?

```cpp
#include <cstdio>
#include <utility>

int main() {
  std::printf("%d %d\n", -1 < 1u, std::cmp_less(-1, 1u));
}
```

A. 1 1
B. 0 1
C. 1 0
D. 0 0

**Answer (B):** 0 1

**Why:** In `-1 < 1u` the signed operand is converted to `unsigned int`, so `-1` becomes `UINT_MAX` and the comparison is false. `std::cmp_less` compares the mathematical values, so it reports that -1 is less than 1. The option `1 1` assumes the built-in comparison behaves like `cmp_less`, which is the usual surprise.

### Question 2 [warmup] ([expr.mul])

In C++11 or later, what is printed?

```cpp
#include <cstdio>

int main() {
  std::printf("%d %d %d %d\n", -7 / 2, -7 % 2, 7 / -2, 7 % -2);
}
```

A. -3 -1 -3 1
B. -4 1 -4 1
C. -3 1 -3 -1
D. -4 -1 -3 1

**Answer (A):** -3 -1 -3 1

**Why:** Division truncates toward zero, so `-7 / 2` and `7 / -2` are both -3. The remainder takes the sign of the dividend, which makes `-7 % 2` equal to -1 and `7 % -2` equal to 1, so that `(a / b) * b + a % b == a` holds. Rounding toward negative infinity, as in the option with -4, is what `>>` does, not `/`.

### Question 3 [warmup] ([basic.fundamental], [expr.pre])

What is printed? `std::size_t` is an unsigned type.

```cpp
#include <cstddef>
#include <cstdio>

int main() {
  std::size_t n = 0;
  std::printf("%d\n", n - 1 > 5);
}
```

A. 0
B. Undefined behavior: the subtraction underflows
C. Ill-formed: a negative value cannot be `std::size_t`
D. 1

**Answer (D):** 1

**Why:** Unsigned arithmetic is modular, so `n - 1` with `n == 0` is `SIZE_MAX`, which is greater than 5, and the program prints 1. There is no undefined behavior here, because unsigned wraparound is defined. The wrapped value is the reason loops of the form `i >= 0` on an unsigned `i` never terminate.

### Question 4 [tricky] ([conv.prom], [expr.pre], [expr.const])

Assume `int` is 32 bits. What is the status of this program?

```cpp
constexpr unsigned short a = 65535;
constexpr auto r = a * a;

int main() { return 0; }
```

A. Ill-formed: the multiplication overflows `int`, so it is not a constant expression
B. Well-formed: unsigned arithmetic wraps, so `r` is 4294836225
C. Well-formed: the product is -131071
D. Ill-formed: narrowing conversion

**Answer (A):** Ill-formed: the multiplication overflows `int`, so it is not a constant expression

**Why:** Both operands are promoted to `int` before the multiplication, so this is a signed multiplication, and 65535 times 65535 is 4294836225, which does not fit in a 32-bit `int`. Signed overflow is undefined, and undefined behavior is not allowed in a constant expression, so the initializer is rejected. Wraparound would only happen if an operand were first converted to `unsigned`.

### Question 5 [tricky] ([expr.mul], [expr.const])

Assume `int` is 32 bits two's complement. What is the status of this declaration?

```cpp
#include <climits>

constexpr int b = INT_MIN % -1;

int main() { return 0; }
```

A. Well-formed: `b` is 0, since the remainder is mathematically 0
B. Well-formed: `b` is `INT_MIN`
C. Ill-formed: the initializer is not a constant expression
D. Well-formed with an unspecified value

**Answer (C):** Ill-formed: the initializer is not a constant expression

**Why:** The quotient `INT_MIN / -1` is 2147483648, which is not representable in `int`. [expr.mul] says that in that case the behavior of both `a / b` and `a % b` is undefined, so the remainder shares the problem, and undefined behavior is not a constant expression. The mathematical value 0 is the tempting answer, but the standard does not give `%` a separate rule.

### Question 6 [tricky] ([conv.integral])

In C++20, assuming `std::int8_t` is an 8-bit two's complement type, what is printed?

```cpp
#include <cstdint>
#include <cstdio>

int main() {
  int big = 200;
  std::int8_t x = big;
  std::printf("%d\n", x);
}
```

A. 200
B. -56
C. 127
D. Undefined behavior

**Answer (B):** -56

**Why:** Since C++20, converting an integer that does not fit to a signed type is modular: 200 is congruent to -56 modulo 256 in the range of an 8-bit signed type. Before C++20 the result was implementation-defined, but it was never undefined. The option 127 describes saturation, which the language does not do.

### Question 7 [standardese] ([utility.intcmp], [basic.fundamental])

In C++20, what is the status of this program?

```cpp
#include <utility>

int main() {
  return std::cmp_less('a', 1) + std::cmp_less(true, 1);
}
```

A. Well-formed: it returns 1
B. Well-formed: `char` is compared as if signed
C. Well-formed, but `bool` is converted to `int` first
D. Ill-formed: `char` and `bool` are not standard or extended integer types

**Answer (D):** Ill-formed: `char` and `bool` are not standard or extended integer types

**Why:** The `std::cmp_*` functions and `std::in_range` require both operands to be standard or extended integer types. Neither `char` nor `bool` is one, so the call is ill-formed. Compilers diagnose it with a static assertion or a failed constraint rather than converting the arguments.

### Question 8 [standardese] ([c.math.abs], [expr.pre])

For a 32-bit two's complement `int`, what does the standard say about `std::abs(INT_MIN)`?

A. It has undefined behavior, because the absolute value is not representable in `int`
B. It returns `INT_MIN`, because the value wraps
C. It returns `INT_MAX`, because the result saturates
D. It returns 2147483648 as an `unsigned int`

**Answer (A):** It has undefined behavior, because the absolute value is not representable in `int`

**Why:** The integer overloads of `std::abs` return an `int` and leave the case where the result is not representable undefined, as the C function does. Wrapping to `INT_MIN` is what many implementations happen to do, which makes it tempting, but the standard does not promise it. The result type never changes to `unsigned`.
