Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

C++  Module 2 – Types, values and expressions

Integer overflow and signed/unsigned conversions

Why unsigned arithmetic wraps but signed overflow is undefined in C++, why -1 < v.size() is false, and how to catch overflow with UBSan and checks.

  • Intermediate
  • 15 minutes
  • Examples run with Clang 21.0.0, GCC 16.2.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 15 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Predict when integer arithmetic overflows and what then happens
  • Avoid signed/unsigned comparison bugs with size()
  • Predict the value a conversion to a narrower integer type keeps
  • Detect overflow with UBSan and with checked arithmetic

Before you start

std::vector<int> scores{70, 85, 92}; holds 3 values, yet -1 < scores.size() is false, and squaring a side of 50,000 in an int is undefined behaviour. Integers in C++ have a fixed number of bits, so a calculation can produce a result that does not fit. What happens then depends on the type. Unsigned arithmetic wraps round modulo 2ᴺ: 0 − 1 is the largest value, and the largest value + 1 is 0. Signed overflow is undefined behaviour: What a program does when it breaks a rule for which the C++ standard sets no requirements, such as reading past the end of an array. The compiler may assume it never happens, so the result can change with the compiler and the optimisation level. More in “Object lifetime and undefined behaviour in C++”: the compiler may assume it never happens, so code that relies on wrapping can be compiled into something else entirely. And when signed and unsigned values meet in one expression, the signed one is usually converted to unsigned, which is why the comparison with scores.size() fails.

Each case below is reproduced with Apple clang 21 and GCC 16, and overflow is caught at run time with UBSan and at compile time with constexpr. The repairs: widen before you multiply, compare with std::cmp_less or std::ssize, and use checked or saturation arithmetic: Arithmetic that stops at the type's limits instead of overflowing: 100 + 100 in std::int8_t gives 127. C++26 adds it to <numeric> as std::saturating_add and its relatives, first named std::add_sat. where a value can really grow too large.

Unsigned arithmetic wraps round

An unsigned type of N bits holds 0 to 2ᴺ − 1, and the standard defines its arithmetic modulo 2ᴺ: every result is reduced into that range. Think of a dial. Going down from 0 lands on the largest value, and going up from the largest value lands on 0. The left dial is that picture for a 32-bit unsigned; the right one, for int, belongs to the next section:

Two dials of 32-bit values: unsigned goes from its maximum on to 0, while int has a seam after INT_MAX that must not be crossed.32-bit values on a dialvalues grow clockwisemax02³¹wrapsunsignedmax + 1 is 0: definedINT_MAXINT_MIN0undefinedintINT_MAX + 1: undefined

Unsigned wraps round; int has a seam you must not cross

Text description of the diagram

Two circles show the values of a 32-bit integer type going round like a dial, growing clockwise.

  • Left, unsigned: 0 is at the top and 2³¹ at the bottom. The largest value, labelled max (2³² − 1), sits just before the top. A solid arrow crosses the top, marked "wraps": max + 1 is 0, and that is defined.
  • Right, int: 0 is at the top. At the bottom the largest int, INT_MAX, meets the smallest, INT_MIN. A dashed arrow across that seam is marked "undefined": INT_MAX + 1 is undefined behaviour, not INT_MIN.
wrap.cpp C++ · wrap.cpp
#include <cstdint>
#include <limits>
#include <print>

int main() {
    unsigned stock = 0;
    --stock;                                    // below 0: wraps round to the largest value
    std::println("0 - 1 as unsigned:       {}", stock);

    unsigned top = std::numeric_limits<unsigned>::max();
    std::println("max + 1 as unsigned:     {}", top + 1u);

    std::uint8_t level = 250;
    level += 10;                                // 260 is stored modulo 256
    std::println("250 + 10 in std::uint8_t: {}", level);
}
Wrapping on both compilers Python · wrap_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra wrap.cpp -o wrap
./wrap
g++-16 -std=c++23 -Wall -Wextra wrap.cpp -o wrap
./wrap
""")

Output

$ clang++ -std=c++23 -Wall -Wextra wrap.cpp -o wrap
$ ./wrap
0 - 1 as unsigned:       4294967295
max + 1 as unsigned:     0
250 + 10 in std::uint8_t: 4
$ g++-16 -std=c++23 -Wall -Wextra wrap.cpp -o wrap
$ ./wrap
0 - 1 as unsigned:       4294967295
max + 1 as unsigned:     0
250 + 10 in std::uint8_t: 4

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 wrap_session.py

Lines starting with $ are the commands typed; everything between them is the output of the command above. Both compilers print the same three lines, without a warning, because nothing here is an error in the language’s eyes. The last line has an extra step. Arithmetic on types narrower than int happens in int: level += 10 computes 250 + 10 = 260 as an int, then converts 260 back to std::uint8_t, keeping it modulo 256, which gives 4. Defined does not mean intended: a stock count that wraps to 4,294,967,295 is still a bug, only a predictable one. Step through that last line:

Interactive · step by step 250 + 10 in a std::uint8_t Step through the last line of wrap.cpp, from the promotion to int to the value stored back in level.
250 + 10 in a std::uint8_t, step 5 of 5. Showing level, level as an int, 250 + 10 in int, 260 modulo 256, level afterwards. In focus: level afterwards.promotedconverted backlevelstd::uint8_t, 250level as an int250250 + 10 in int260260 modulo 2564level afterwards4

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Near the top. level holds 250. A std::uint8_t holds 0 to 255, so 250 sits near the top of its dial.
  2. Promoted. level += 10 first promotes level to int, as arithmetic does with every type narrower than int.
  3. The sum. The addition happens in int: 250 + 10 = 260, which an int holds easily.
  4. Converted back. Storing 260 back into level converts it to std::uint8_t, which keeps it modulo 256: 260 − 256 = 4.
  5. Defined, still a bug. level is now 4, as both builds printed, and neither compiler warned, because the wrap is defined. A level that falls from 250 to 4 when 10 is added is still a bug, only a predictable one.

Checkpoint

Check: Unsigned wrap-around

  1. Question 1 of 2 unsigned is 32 bits here. What is the value of 3u - 5u?

    Type a number.

    A hint

    Go down from 0 on the dial; 0 − 1 is the largest value.

    Show the answer: Question 1 of 2

    Answer: 4294967294

    3 − 5 is −2, which unsigned arithmetic reduces modulo 2³²: 4,294,967,296 − 2 = 4,294,967,294, one below the largest unsigned value.

  2. Question 2 of 2 What does the standard say about 0u - 1u?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It is defined, and gives the largest unsigned value

    wrap.cpp printed 4294967295 for 0 − 1 and 0 for the largest value + 1, without a warning: both are defined, and both can still be bugs in a program that counts things.

Signed overflow is undefined behaviour

For signed types the standard makes no such promise. Since C++20, two’s complement is the only representation it allows, yet the note that P1236R1 added says it plainly: overflow for signed arithmetic is undefined behaviour. This program squares a side of 50,000, whose square, 2,500,000,000, is larger than the largest int, 2,147,483,647:

area.cpp C++ · area.cpp
#include <print>

int main() {
    int side = 50'000;
    long long wrong = side * side;         // int * int overflows before the result is widened
    long long right = 1LL * side * side;   // long long * int, then * int: no overflow
    std::println("wrong: {}", wrong);
    std::println("right: {}", right);
}
Signed overflow under UBSan Python · area_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra -fsanitize=undefined area.cpp -o area
./area
g++-16 -std=c++23 -Wall -Wextra -fsanitize=undefined area.cpp -o area
./area
""")

Output

$ clang++ -std=c++23 -Wall -Wextra -fsanitize=undefined area.cpp -o area
$ ./area
area.cpp:5:28: runtime error: signed integer overflow: 50000 * 50000 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior area.cpp:5:28 
wrong: -1794967296
right: 2500000000
$ g++-16 -std=c++23 -Wall -Wextra -fsanitize=undefined area.cpp -o area
$ ./area
area.cpp:5:28: runtime error: signed integer overflow: 50000 * 50000 cannot be represented in type 'int'
wrong: -1794967296
right: 2500000000

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 area_session.py

-fsanitize=undefined builds the program with sanitizer: A compiler option, such as -fsanitize=address or -fsanitize=undefined, that builds extra checks into a program, so that memory errors and undefined behaviour are reported, with their source line, while it runs. More in “Finding memory bugs with AddressSanitizer and UBSan” (UBSan), which checks operations such as signed arithmetic while the program runs and reports the first one that goes wrong, with its file, line and column. Both compilers’ UBSan point at line 5. The value printed for wrong, -1,794,967,296, is what the processor’s wrapping instruction happened to produce, but nothing obliges the compiler to use that instruction or to keep the result.

The bug is the order of events. side * side multiplies two ints, so the product is an int and overflows; only then is it converted to long long, too late. 1LL * side * side makes the first operand a long long, so each multiplication is done in 64 bits. The order matters: side * side * 1LL still overflows, because the multiplications run from left to right and the first one is still int * int. Step through both products:

Interactive · step by step Where side * side overflows, and 1LL * side * side does not Step through the two products of area.cpp one operation at a time. Watch the type each multiplication is done in.
Where side * side overflows, and 1LL * side * side does not, step 6 of 6. Showing side, side * side (overflows: undefined), wrong (−1,794,967,296), 1LL * side (long long, 50,000), (1LL * side) * side, right (2,500,000,000). In focus: side * side.sideint, 50,000side * sideoverflows: undefinedwrong−1,794,967,2961LL * sidelong long, 50,000(1LL * side) * sidelong long times intright2,500,000,000

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. int times int. side is an int holding 50,000. Both operands of side * side are int, so the product is computed as an int.
  2. The overflow. 50,000 × 50,000 = 2,500,000,000, more than 2,147,483,647, the largest int: signed overflow, which is undefined behaviour. UBSan reported it at line 5, column 28.
  3. Too late. The wrapping instruction of this build happened to give −1,794,967,296, and only that value is converted to long long. The conversion comes after the damage.
  4. Widen first. 1LL * side: the first operand is a long long, so side is converted to long long and the product is computed in 64 bits.
  5. Still 64 bits. Then * side is a long long times an int, again computed in 64 bits. 2,500,000,000 fits easily below the largest long long, about 9.2 × 10¹⁸.
  6. Order matters. side * side * 1LL still overflows: the multiplications run from left to right, and the first of them is still int times int.

Widening the result instead of an operand

long long area = side * side; overflows before the long long is involved. Widen an operand, so that the multiplication itself happens in 64 bits: long long area = 1LL * side * side;.

The compiler assumes overflow never happens

Undefined behaviour is not “the program crashes” or “the value wraps”. It is permission for the compiler to assume that the situation cannot arise, and optimisers use that permission. This function tries to detect overflow by checking whether x + 1 became smaller than x:

overflow_check.cpp C++ · overflow_check.cpp
#include <climits>
#include <print>

// Meant to detect overflow, but it relies on x + 1 wrapping round, which a signed int never has to do.
bool will_overflow(int x) {
    return x + 1 < x;
}

int main() {
    std::println("will_overflow(INT_MAX): {}", will_overflow(INT_MAX));
}
One function, three answers Python · overflow_check_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra overflow_check.cpp -o check
./check
clang++ -std=c++23 -Wall -Wextra -O2 overflow_check.cpp -o check
./check
g++-16 -std=c++23 -Wall -Wextra overflow_check.cpp -o check
./check
g++-16 -std=c++23 -Wall -Wextra -fsanitize=undefined overflow_check.cpp -o check
./check
""")

Output

$ clang++ -std=c++23 -Wall -Wextra overflow_check.cpp -o check
$ ./check
will_overflow(INT_MAX): true
$ clang++ -std=c++23 -Wall -Wextra -O2 overflow_check.cpp -o check
$ ./check
will_overflow(INT_MAX): false
$ g++-16 -std=c++23 -Wall -Wextra overflow_check.cpp -o check
$ ./check
will_overflow(INT_MAX): false
$ g++-16 -std=c++23 -Wall -Wextra -fsanitize=undefined overflow_check.cpp -o check
$ ./check
overflow_check.cpp:6:14: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
will_overflow(INT_MAX): true

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 overflow_check_session.py

Apple clang without optimisation computes x + 1 with a wrapping instruction and says true. With -O2 it says false: since x + 1 cannot overflow in a valid program, x + 1 < x is always false, and the compiler replaced the whole test with false. GCC simplifies the comparison the same way even without optimisation. Under UBSan the addition really happens, so the report appears and the answer is true again. A check that depends on overflow cannot detect overflow. Compare against the limit before you add instead: x == INT_MAX, or in general x > INT_MAX - y for a positive y.

Overflow in a constant expression is an error

When a calculation runs at compile time, in a constexpr variable or a static_assert, the compiler is required to reject undefined behaviour instead of assuming it away:

constexpr_overflow.cpp C++ · constexpr_overflow.cpp
#include <climits>

constexpr int next(int x) {
    return x + 1;
}

constexpr int fine = next(41);          // evaluated while compiling: 42
constexpr int broken = next(INT_MAX);   // overflow while compiling: an error

int main() {
    return fine + broken;
}
Overflow found while compiling Python · constexpr_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra -c constexpr_overflow.cpp
g++-16 -std=c++23 -Wall -Wextra -c constexpr_overflow.cpp
""")

Output

$ clang++ -std=c++23 -Wall -Wextra -c constexpr_overflow.cpp
constexpr_overflow.cpp:8:15: error: constexpr variable 'broken' must be initialized by a constant expression
    8 | constexpr int broken = next(INT_MAX);   // overflow while compiling: an error
      |               ^        ~~~~~~~~~~~~~
constexpr_overflow.cpp:4:14: note: value 2147483648 is outside the range of representable values of type 'int'
    4 |     return x + 1;
      |              ^
constexpr_overflow.cpp:8:24: note: in call to 'next(2147483647)'
    8 | constexpr int broken = next(INT_MAX);   // overflow while compiling: an error
      |                        ^~~~~~~~~~~~~
1 error generated.
[exit status 1]
$ g++-16 -std=c++23 -Wall -Wextra -c constexpr_overflow.cpp
constexpr_overflow.cpp:8:28:   in 'constexpr' expansion of 'next(2147483647)'
    8 | constexpr int broken = next(INT_MAX);   // overflow while compiling: an error
      |                        ~~~~^~~~~~~~~
constexpr_overflow.cpp:4:14: error: overflow in constant expression [-fpermissive]
    4 |     return x + 1;
      |            ~~^~~
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 constexpr_session.py

fine compiles, and broken stops both compilers with the overflowing call spelled out. That makes constexpr evaluation a cheap way to test arithmetic helpers: a static_assert on an edge case, such as the largest input, runs every time the file compiles.

Key idea

Signed overflow is undefined behaviour, so it has to be prevented rather than detected afterwards: widen an operand before the operation, and compare against the limit before you add.

Checkpoint

Check: Signed overflow

  1. Question 1 of 3 Apple clang with -O2 printed will_overflow(INT_MAX): false, while the build without optimisation printed true. Why may the two builds differ?

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: x + 1 < x can only be true after an overflow, which a valid program never has, so the compiler made the test false

    A check that relies on signed overflow cannot detect it: GCC folded the same comparison to false even without optimisation. Compare against the limit first, as in x == INT_MAX.

  2. Question 2 of 3 x and y are ints and y is positive. Which test says that x + y would overflow, before anything overflows?

    Choose one answer.

    Show the answer: Question 2 of 3

    Answer: x > INT_MAX - y

    Compare against the limit before the operation: x > INT_MAX - y for a positive y, which is what the lesson's x == INT_MAX does for y = 1.

  3. Question 3 of 3 What do both compilers do with constexpr int broken = next(INT_MAX);?

    Choose one answer.

    Show the answer: Question 3 of 3

    Answer: Stop the build with an error, naming the overflow

    constexpr evaluation turns undefined behaviour into a compile error, so a static_assert on an edge case, such as the largest input, tests an arithmetic helper every time the file compiles.

Mixing signed and unsigned makes negative numbers huge

std::vector, std::string and the other standard containers report their size as std::size_t, an unsigned type. When an expression combines it with an int, the usual arithmetic conversions: The rules that give both operands of an arithmetic or comparison operator one common type. When a signed and an unsigned integer meet and the unsigned type is at least as wide, the signed value is converted to unsigned, so −1 < v.size() is false. turn the int into the unsigned type, because unsigned wins when the unsigned type is at least as wide. A negative number does not survive that:

sign_compare.cpp C++ · sign_compare.cpp
#include <iterator>
#include <print>
#include <utility>
#include <vector>

int main() {
    std::vector<int> scores{70, 85, 92};
    int wanted = -1;                          // "no score": a common sentinel

    std::println("wanted < scores.size():            {}", wanted < scores.size());
    std::println("std::cmp_less(wanted, size):       {}", std::cmp_less(wanted, scores.size()));
    std::println("wanted < std::ssize(scores):       {}", wanted < std::ssize(scores));
    std::println("scores.size() - 4:                 {}", scores.size() - 4);
}
Comparing -1 with a size Python · sign_compare_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra sign_compare.cpp -o sign_compare
./sign_compare
g++-16 -std=c++23 -Wall -Wextra sign_compare.cpp -o sign_compare
./sign_compare
""")

Output

$ clang++ -std=c++23 -Wall -Wextra sign_compare.cpp -o sign_compare
sign_compare.cpp:10:66: warning: comparison of integers of different signs: 'int' and 'size_type' (aka 'unsigned long') [-Wsign-compare]
   10 |     std::println("wanted < scores.size():            {}", wanted < scores.size());
      |                                                           ~~~~~~ ^ ~~~~~~~~~~~~~
1 warning generated.
$ ./sign_compare
wanted < scores.size():            false
std::cmp_less(wanted, size):       true
wanted < std::ssize(scores):       true
scores.size() - 4:                 18446744073709551615
$ g++-16 -std=c++23 -Wall -Wextra sign_compare.cpp -o sign_compare
sign_compare.cpp: In function 'int main()':
sign_compare.cpp:10:66: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   10 |     std::println("wanted < scores.size():            {}", wanted < scores.size());
      |                                                           ~~~~~~~^~~~~~~~~~~~~~~
$ ./sign_compare
wanted < scores.size():            false
std::cmp_less(wanted, size):       true
wanted < std::ssize(scores):       true
scores.size() - 4:                 18446744073709551615

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 sign_compare_session.py

wanted < scores.size() converts -1 to a std::size_t, which on these 64-bit platforms is 18,446,744,073,709,551,615, the largest value, so the comparison is false. Both compilers warn about that line with -Wall -Wextra, and a build that treats warnings as errors catches it. The last line shows the same conversion in reverse: scores.size() - 4 is unsigned arithmetic, so 3 − 4 wraps round to the largest value instead of giving -1. Step through the program’s four lines:

Interactive · step by step How -1 < scores.size() becomes false Step through sign_compare.cpp. The first comparison converts -1 before it compares; the two fixes compare values instead.
How -1 < scores.size() becomes false, step 7 of 7. Showing wanted, scores.size(), −1 as std::size_t, wanted < scores.size(), std::cmp_less(…), wanted < std::ssize(…), scores.size() − 4. In focus: scores.size() − 4.convertedwantedint, −1scores.size()std::size_t, 3−1 as std::size_t18446744073709551615wanted < scores.size()falsestd::cmp_less(…)truewanted < std::ssize(…)truescores.size() − 418446744073709551615

The drawing shows the whole scene; its 7 steps are listed below.

Every step as text
  1. Two types. wanted is −1, an int used as a "no score" mark. scores.size() is 3, a std::size_t, which is unsigned and 64 bits wide here.
  2. One common type. To compare them, the usual arithmetic conversions give both operands one type. The unsigned type is at least as wide as int, so it wins, and wanted is converted to std::size_t.
  3. The largest value. −1 has no unsigned value, so it becomes 2⁶⁴ − 1 = 18,446,744,073,709,551,615, the largest std::size_t.
  4. false. The comparison is now 18,446,744,073,709,551,615 < 3, which is false. Both compilers warned about this line with -Wall -Wextra.
  5. std::cmp_less. std::cmp_less(wanted, scores.size()) compares the mathematical values, −1 and 3, whatever the two types are: true.
  6. std::ssize. std::ssize(scores) gives the size as a signed type, so wanted < std::ssize(scores) compares −1 with 3 as two signed values: true.
  7. The same in reverse. scores.size() − 4 is unsigned arithmetic as well: 3 − 4 wraps round to 18,446,744,073,709,551,615 instead of giving −1.

There are three good fixes, and rule ES.100 of the C++ Core Guidelines is behind all of them: don’t mix signed and unsigned arithmetic.

  • std::cmp_less(a, b) from <utility> (C++20) compares two integers by their mathematical values, whatever their types. Its family includes cmp_equal, cmp_greater and the others.
  • std::ssize(c) from <iterator> (C++20) returns a container’s size as a signed type, so the comparison is between two signed values.
  • Keep sizes in a signed type from the start when you do arithmetic with them, and convert once, deliberately.

Checkpoint

Check: Mixing signed and unsigned

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    int n = -2;
    unsigned u = 1;
    std::println("{}", n < u);
    Show the answer: Question 1 of 2

    Answer: false

    The usual arithmetic conversions make both operands unsigned, because unsigned int is as wide as int. -2 becomes 2³² − 2, so the comparison is false.

  2. Question 2 of 2 Which of these compares an int with a container's size by their mathematical values?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: std::cmp_less(wanted, scores.size())

    std::cmp_less from <utility> compares values, and std::ssize from <iterator> gives a signed size; either avoids the conversion of -1.

Converting to a narrower integer type keeps the low bits

Assigning a value to an integer type that cannot hold it is not overflow. Since C++20 the result is defined: the value is reduced modulo 2ᴺ for the target’s N bits, which keeps the low N bits of its two’s complement form.

conversions.cpp C++ · conversions.cpp
#include <cstdint>
#include <print>
#include <type_traits>

int main() {
    // Converting to an integer type that cannot hold the value keeps the low bits (defined since C++20).
    int from_big = static_cast<int>(3'000'000'000u);     // 3,000,000,000 - 2^32
    std::uint8_t from_300 = static_cast<std::uint8_t>(300);  // 300 - 256
    unsigned from_minus_one = static_cast<unsigned>(-1);  // 2^32 - 1
    std::println("{} {} {}", from_big, from_300, from_minus_one);

    // Arithmetic on small types happens in int: the operands are promoted first.
    unsigned char a = 200, b = 100;
    auto sum = a + b;
    static_assert(std::is_same_v<decltype(sum), int>);
    std::println("200 + 100 with unsigned char operands: {} (an int)", sum);
}
Conversions and promotions Python · conversions_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra conversions.cpp -o conversions
./conversions
g++-16 -std=c++23 -Wall -Wextra conversions.cpp -o conversions
./conversions
""")

Output

$ clang++ -std=c++23 -Wall -Wextra conversions.cpp -o conversions
$ ./conversions
-1294967296 44 4294967295
200 + 100 with unsigned char operands: 300 (an int)
$ g++-16 -std=c++23 -Wall -Wextra conversions.cpp -o conversions
$ ./conversions
-1294967296 44 4294967295
200 + 100 with unsigned char operands: 300 (an int)

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 conversions_session.py

3,000,000,000 becomes -1,294,967,296 (3,000,000,000 − 2³²), 300 becomes 44 (300 − 256), and -1 becomes 4,294,967,295 (2³² − 1). Defined behaviour, but rarely what anyone wants, so make such conversions visible with static_cast, as the program does. The second half shows integral promotion: The conversion of an operand narrower than int, such as bool, char, unsigned char or short, to int before arithmetic, so that 200 + 100 with unsigned char operands is the int 300.: before arithmetic, operands narrower than int, such as unsigned char, short and bool, are promoted to int. That is why 200 + 100 gives 300 instead of wrapping in 8 bits, and why the type of the sum is int. Step through the bits that each conversion keeps:

Interactive · step by step Keeping the low bits, in the conversions of conversions.cpp Step through the three conversions and the promotion of conversions.cpp. Each one keeps bits; none of them overflows.
Keeping the low bits, in the conversions of conversions.cpp, step 5 of 5. Showing 300, std::uint8_t: 44, 3,000,000,000u, int: −1,294,967,296, −1, unsigned: 4,294,967,295, 200 + 100, int: 300.3001 0010 1100: 9 bitsstd::uint8_t: 44low 8 bits: 0010 11003,000,000,000u0xB2D05E00int: −1,294,967,296same 32 bits, signed−132 ones: 0xFFFFFFFFunsigned: 4,294,967,2952³² − 1200 + 100two unsigned charsint: 300promoted first

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. 300 into 8 bits. 300 needs 9 bits, 1 0010 1100. std::uint8_t keeps the low 8, 0010 1100, which is 44: the same as 300 − 256.
  2. 3,000,000,000 into int. 3,000,000,000 is 0xB2D05E00. As a 32-bit int the same bits mean 3,000,000,000 − 2³² = −1,294,967,296, a result C++20 defines.
  3. −1 into unsigned. −1 in two's complement is 32 ones. As unsigned, those bits are 2³² − 1 = 4,294,967,295.
  4. Promotion. Before arithmetic, operands narrower than int are promoted to int, so 200 + 100 with unsigned char operands is 300, an int, and nothing wraps in 8 bits.
  5. Defined, and visible. Every result here is defined, and both builds printed the same. Write such conversions with static_cast, as the program does, so that a reader sees them.

Programmer Calculator (Bitwise) Type 3000000000 and switch to 32-bit signed to see the same bits read as -1294967296.

Checkpoint

Check: Conversions and promotion

  1. Question 1 of 2 What is static_cast<std::uint8_t>(260)?

    Type a number.

    A hint

    std::uint8_t keeps the value modulo 256.

    Show the answer: Question 1 of 2

    Answer: 4

    260 is 1 0000 0100 in 9 bits; std::uint8_t keeps the low 8 bits, 0000 0100, which is 4: the same as 260 − 256, and the value level ended with in wrap.cpp.

  2. Question 2 of 2 What does this print?

    Read the code, then choose one answer.

    unsigned char a = 200, b = 100;
    auto sum = a + b;
    std::println("{}", sum);
    Show the answer: Question 2 of 2

    Answer: 300

    Integral promotion turns operands narrower than int into int before arithmetic, which is why conversions.cpp printed 300 and its static_assert confirmed that the sum is an int.

UBSan finds overflow while you test; checked and saturating arithmetic prevent it

Three tools cover most needs.

UBSan, while you test. -fsanitize=undefined is available in both compilers, and Clang’s documentation lists macOS, Linux and Windows among its platforms. It reports signed overflow, and also division of INT_MIN by -1. Unsigned wrapping is not undefined, so it is not part of -fsanitize=undefined; Clang can check it with -fsanitize=unsigned-integer-overflow when a wrap would be a bug in your program.

Checked arithmetic, where an input can be too large. GCC and Clang provide __builtin_add_overflow, __builtin_sub_overflow and __builtin_mul_overflow, which compute the exact result, store it in the result’s type, keeping the low bits when it does not fit, and return whether it overflowed. Wrapped in a function that returns std::optional, a caller cannot forget the check:

checked.cpp C++ · checked.cpp
#include <cstdint>
#include <limits>
#include <optional>
#include <print>
#include <utility>

// The product of a and b, or nothing when it does not fit in std::int64_t.
// __builtin_mul_overflow (GCC and Clang) computes the exact product and reports whether it fitted.
std::optional<std::int64_t> safe_mul(std::int64_t a, std::int64_t b) {
    std::int64_t product;
    if (__builtin_mul_overflow(a, b, &product)) return std::nullopt;
    return product;
}

int main() {
    constexpr std::int64_t lowest = std::numeric_limits<std::int64_t>::min();
    const std::pair<std::int64_t, std::int64_t> cases[] = {
        {3'000'000'000, 3},
        {3'037'000'499, 3'037'000'499},
        {3'037'000'500, 3'037'000'500},
        {lowest, 1},
        {lowest, -1},
    };
    for (auto [a, b] : cases) {
        if (auto product = safe_mul(a, b)) std::println("{} * {} = {}", a, b, *product);
        else std::println("{} * {} does not fit", a, b);
    }
}
A multiplication that reports overflow Python · checked_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra checked.cpp -o checked
./checked
g++-16 -std=c++23 -Wall -Wextra checked.cpp -o checked
./checked
""")

Output

$ clang++ -std=c++23 -Wall -Wextra checked.cpp -o checked
$ ./checked
3000000000 * 3 = 9000000000
3037000499 * 3037000499 = 9223372030926249001
3037000500 * 3037000500 does not fit
-9223372036854775808 * 1 = -9223372036854775808
-9223372036854775808 * -1 does not fit
$ g++-16 -std=c++23 -Wall -Wextra checked.cpp -o checked
$ ./checked
3000000000 * 3 = 9000000000
3037000499 * 3037000499 = 9223372030926249001
3037000500 * 3037000500 does not fit
-9223372036854775808 * 1 = -9223372036854775808
-9223372036854775808 * -1 does not fit

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 checked_session.py

The edge cases are the instructive ones. 3,037,000,499² fits in 64 bits and 3,037,000,500² does not, because the square root of the largest std::int64_t is about 3,037,000,499.98. And the smallest std::int64_t times -1 overflows, since the range runs to -2⁶³ but only up to 2⁶³ − 1. The same applies to -x, std::abs(x) and x / -1 when x is the smallest int, long or long long.

Big Number Calculator Check exact products such as 3037000500 × 3037000500 against the 64-bit limit.

Saturating arithmetic, where a clamp is the right answer. Sometimes the best result of an overflow is the nearest limit: a volume control, a pixel brightness, a counter that should stop at its maximum. C++26 adds these functions to <numeric>. They were adopted as std::add_sat and its relatives (P0543R3), and renamed std::saturating_add, std::saturating_sub, std::saturating_mul and std::saturating_div by P4052R0, which also raised the feature-test macro __cpp_lib_saturation_arithmetic from 202311 to 202603 so that code can tell the names apart. The two standard libraries here stand on either side of the rename:

saturating.cpp C++ · saturating.cpp
#include <climits>
#include <cstdint>
#include <limits>
#include <numeric>
#include <print>
#include <version>

// Adds and stops at the type's limits instead of overflowing. C++26 calls the standard
// function std::saturating_add; the first C++26 drafts called it std::add_sat.
template <class T>
constexpr T clamp_add(T a, T b) {
#if __cpp_lib_saturation_arithmetic >= 202603L
    return std::saturating_add(a, b);
#elif __cpp_lib_saturation_arithmetic >= 202311L
    return std::add_sat(a, b);
#else
    T sum;
    if (!__builtin_add_overflow(a, b, &sum)) return sum;
    return b > 0 ? std::numeric_limits<T>::max() : std::numeric_limits<T>::min();
#endif
}

int main() {
#ifdef __cpp_lib_saturation_arithmetic
    std::println("__cpp_lib_saturation_arithmetic = {}", __cpp_lib_saturation_arithmetic);
#else
    std::println("no saturation arithmetic in this library");
#endif
    std::println("int8: 100 + 100 = {}", clamp_add<std::int8_t>(100, 100));
    std::println("uint8: 250 + 10 = {}", clamp_add<std::uint8_t>(250, 10));
    std::println("int: INT_MAX + 1 = {}", clamp_add(INT_MAX, 1));
    std::println("int: INT_MIN + -1 = {}", clamp_add(INT_MIN, -1));
}
One file, two names, the same results Python · saturating_session.py
from session import run

run("""
clang++ -std=c++26 -Wall -Wextra saturating.cpp -o saturating
./saturating
g++-16 -std=c++26 -Wall -Wextra saturating.cpp -o saturating
./saturating
g++-16 -std=c++23 -Wall -Wextra saturating.cpp -o saturating
./saturating
""")

Output

$ clang++ -std=c++26 -Wall -Wextra saturating.cpp -o saturating
$ ./saturating
__cpp_lib_saturation_arithmetic = 202311
int8: 100 + 100 = 127
uint8: 250 + 10 = 255
int: INT_MAX + 1 = 2147483647
int: INT_MIN + -1 = -2147483648
$ g++-16 -std=c++26 -Wall -Wextra saturating.cpp -o saturating
$ ./saturating
__cpp_lib_saturation_arithmetic = 202603
int8: 100 + 100 = 127
uint8: 250 + 10 = 255
int: INT_MAX + 1 = 2147483647
int: INT_MIN + -1 = -2147483648
$ g++-16 -std=c++23 -Wall -Wextra saturating.cpp -o saturating
$ ./saturating
no saturation arithmetic in this library
int8: 100 + 100 = 127
uint8: 250 + 10 = 255
int: INT_MAX + 1 = 2147483647
int: INT_MIN + -1 = -2147483648

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 saturating_session.py

With -std=c++26, Apple clang’s libc++ reports 202311 and offers only std::add_sat, while GCC 16’s libstdc++ reports 202603 and offers only std::saturating_add. The #if tests choose whichever exists, and in C++23 mode, where neither does, the file falls back to __builtin_add_overflow and clamps by hand. All three builds print the same results: 100 + 100 in std::int8_t stops at 127, and 250 + 10 in std::uint8_t at 255.

The three tools, and the plain repair of a wider type, differ in when they act and in what becomes of a result that does not fit:

Tool When it acts A result that does not fit
-fsanitize=undefined (UBSan) While you test Reported, with its file, line and column
__builtin_mul_overflow in safe_mul On every call No value: std::nullopt
std::saturating_add On every call The nearest limit: 127 for 100 + 100 in std::int8_t
A wider type, 1LL * a * b On every call None, while the result fits in 64 bits

Key idea

Choose by what a result that does not fit should become: a report while you test, no value at all, or the nearest limit.

Checkpoint

Check: Catching and preventing overflow

  1. Question 1 of 2 What does safe_mul(3'037'000'500, 3'037'000'500) return?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: std::nullopt, because the product does not fit in std::int64_t

    checked.cpp printed "3037000500 * 3037000500 does not fit": __builtin_mul_overflow returned true, and safe_mul turned that into an empty std::optional the caller must test.

  2. Question 2 of 2 What does clamp_add<std::int8_t>(100, 100) from saturating.cpp return?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 127

    The function used std::saturating_add in GCC 16's library, std::add_sat in libc++, and __builtin_add_overflow in C++23 mode: 100 + 100 stopped at 127 in every build.

Practise: overflow and conversions

Now check what stays defined and what does not. Questions arrive one by one, the weakest idea first, each with feedback on every option:

Practice that adapts to you

Practise this lesson

11 questions about 5 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 11 unsigned is 32 bits here. What value does u hold afterwards?

    Read the code, then choose one answer.

    unsigned u = 0;
    u = u - 1;
    Show the answer: Question 1 of 11

    Answer: 4294967295

    Unsigned arithmetic is defined modulo 2³², so 0 − 1 wraps round to 2³² − 1, the largest unsigned value. Only signed overflow is undefined.

  2. Question 2 of 11 What does level hold afterwards?

    Read the code, then choose one answer.

    std::uint8_t level = 200;
    level += 100;
    Show the answer: Question 2 of 11

    Answer: 44

    As in wrap.cpp, where 250 + 10 gave 4, the sum is computed in int and converted back to std::uint8_t, which keeps it modulo 256.

  3. Question 3 of 11 GCC turns return x + 1 < x;, with x an int, into return false; even without optimisation. Why is that allowed?

    Choose one answer.

    Show the answer: Question 3 of 11

    Answer: Signed overflow is undefined, so the compiler may assume x + 1 never overflows

    In a program without undefined behaviour x + 1 is always greater than x, so the comparison is always false. Test against the limit before adding, for example x == INT_MAX.

  4. Question 4 of 11 What does the standard say about the result?

    Read the code, then choose one answer.

    int side = 50'000;
    long long area = side * side;
    Show the answer: Question 4 of 11

    Answer: The behaviour is undefined, because side * side overflows int before it is widened

    Both operands are int, so the product is computed as an int, and 2,500,000,000 does not fit. The wrapped value that many builds print is not guaranteed. Write 1LL * side * side.

  5. Question 5 of 11 w and h are int. Which line computes their product without overflowing int?

    Choose one answer.

    Show the answer: Question 5 of 11

    Answer: long long r = 1LL * w * h;

    Multiplication runs from left to right, so only when the first operand is a long long is every step done in 64 bits. In the other three, w * h is computed as an int first.

  6. Question 6 of 11 In -1 < v.size(), which type is -1 converted to before the comparison?

    Choose one answer.

    Show the answer: Question 6 of 11

    Answer: std::size_t

    The usual arithmetic conversions turn -1 into the largest std::size_t, 18,446,744,073,709,551,615 here, so the comparison is false.

  7. Question 7 of 11 What does std::cmp_less(-1, v.size()) return for a vector v with two elements?

    Choose one answer.

    Show the answer: Question 7 of 11

    Answer: true

    std::cmp_less compares the mathematical values, so -1 is less than 2. The plain comparison -1 < v.size() converts -1 to std::size_t, the largest value, and gives false.

  8. Question 8 of 11 What is the type of a + b when a and b are both unsigned char?

    Choose one answer.

    Show the answer: Question 8 of 11

    Answer: int

    conversions.cpp checked it with static_assert(std::is_same_v<decltype(sum), int>): the sum of two unsigned chars is an int, which is why 200 + 100 gave 300.

  9. Question 9 of 11 Which of these are well-defined in C++23?

    Choose every answer that is right.

    Show the answer: Question 9 of 11

    Answer:

    • static_cast<int>(3000000000u)
    • UINT_MAX + 1u
    • static_cast<std::uint8_t>(300)

    Conversions to an integer type keep the low bits (300 becomes 44, and since C++20 3,000,000,000 becomes -1,294,967,296), and unsigned arithmetic wraps. INT_MAX + 1 and -INT_MIN overflow int, which is undefined.

  10. Question 10 of 11 Does -fsanitize=undefined report an unsigned value that wraps round?

    Choose one answer.

    Show the answer: Question 10 of 11

    Answer: No, because unsigned wrapping is not undefined; Clang can check it with -fsanitize=unsigned-integer-overflow

    A wrap can still be a bug in your program; then Clang's -fsanitize=unsigned-integer-overflow reports it, beyond what -fsanitize=undefined covers.

  11. Question 11 of 11 A volume control in a std::uint8_t must stay at 255 when the user keeps pressing "louder". Which repair fits?

    Choose one answer.

    Show the answer: Question 11 of 11

    Answer: Saturating addition, such as std::saturating_add

    Choose by what a result that does not fit should become: here the nearest limit, which is exactly what saturating arithmetic gives, as 250 + 10 in std::uint8_t stopped at 255 in saturating.cpp.

Interview questions

Fresher · What happens when an unsigned int overflows, and when an int does?

Unsigned arithmetic is defined modulo 2ᴺ, so it wraps: the largest unsigned int plus 1 is 0, and 0 minus 1 is the largest value. Signed overflow, such as INT_MAX + 1, is undefined behaviour, even though C++20 requires two’s complement. The compiler may assume it never happens: it can fold a check such as x + 1 < x to false, and the program may print a wrapped value, a different value or something else. Converting an out-of-range value to a signed type is different: since C++20 that is defined and keeps the low bits. Catch overflow with -fsanitize=undefined while testing, and prevent it with wider types or checked arithmetic.

The next questions usually probe whether you would trust a wrapped value. Try both, and read the reasoning behind every option:

Checkpoint

Interview round: two follow-up questions

  1. Question 1 of 2 The interviewer follows up: your test printed -2147483648 for INT_MAX + 1, which is the wrap you wanted. Is the code correct?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: No. The overflow is undefined behaviour; that value is what one build produced, and another build may do something else

    If the wrap is really wanted, do the arithmetic in an unsigned type, where wrapping is defined, and convert back; otherwise prevent the overflow with a wider type or a check against the limit.

  2. Question 2 of 2 And then: is static_cast<int>(3'000'000'000u) undefined behaviour as well?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: No. Since C++20 the conversion keeps the low 32 bits, so the result is -1,294,967,296

    Since C++20 a conversion to an integer type keeps the value modulo 2ᴺ, the low N bits of its two's complement form. It is defined, and rarely what anyone wants, so write it with static_cast where it is meant.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    This loop prints a vector backwards: for (std::size_t i = v.size() - 1; i >= 0; --i) std::cout << v[i]; It prints the elements and then garbage until the program crashes, and with an empty vector it crashes at once. Explain both, with the numbers involved, and give two correct ways to write it.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    A binary search over a sorted array of 1.5 billion entries computes int mid = (lo + hi) / 2; and crashes, but only on the largest inputs. Why, what would UBSan report, and what are the correct ways to compute the midpoint?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • Unsigned arithmetic wraps modulo 2ᴺ: defined, but often still a bug.
  • Signed overflow is undefined behaviour. The compiler may assume it cannot happen, so a check like x + 1 < x can be compiled to false: compare against the limit before the operation, and widen before it, 1LL * a * b, never long long r = a * b;.
  • In a constant expression, overflow is a compile error, which makes static_assert a cheap test of edge cases.
  • An int compared with a size() becomes unsigned, so -1 < v.size() is false. Use std::cmp_less, std::ssize or signed sizes.
  • Converting to a narrower integer type keeps the low bits (defined since C++20), and arithmetic on narrow types happens in int.
  • Test with -fsanitize=undefined; check with __builtin_mul_overflow; clamp with C++26 saturation arithmetic, std::saturating_add in GCC 16 and still std::add_sat in Apple clang 21’s libc++.

Terms in this lesson

integral promotion
The conversion of an operand narrower than int, such as bool, char, unsigned char or short, to int before arithmetic, so that 200 + 100 with unsigned char operands is the int 300.
saturation arithmetic
Arithmetic that stops at the type's limits instead of overflowing: 100 + 100 in std::int8_t gives 127. C++26 adds it to <numeric> as std::saturating_add and its relatives, first named std::add_sat.
usual arithmetic conversions
The rules that give both operands of an arithmetic or comparison operator one common type. When a signed and an unsigned integer meet and the unsigned type is at least as wide, the signed value is converted to unsigned, so −1 < v.size() is false.

Corrections

  • The section on checked arithmetic now says that the overflow builtins always store the result, keeping its low bits when it does not fit, and report whether it overflowed.
  • The section on constant expressions now says that both compilers name the overflowing call; only Clang prints the value 2147483648.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.