← Fundamentals
Fundamentals

Integers, signs, and overflow

When a result does not fit its type, does your language wrap, stop, or widen?

Follow integer width through interpretation, arithmetic and storage.

Outcome

Predict signed and unsigned ranges, overflow and narrowing in each language, and choose a type and an explicit edge policy (widen, wrap, check or saturate) for a result.

Terminology (9)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Fixed-width integer
An integer type with a set number of bits, and so a set range.
Unsigned
A type whose bit patterns all mean values from 0 upward: 0 to 2ⁿ − 1.
Two’s complement
The signed encoding in which the top bit is worth −2ⁿ⁻¹, giving −2ⁿ⁻¹ to 2ⁿ⁻¹ − 1.
Overflow
An arithmetic result outside the range of the type the operation is done in.
Wrapping
Keeping the low n bits of a result, which is the value modulo 2ⁿ.
Saturating
Replacing an out-of-range result with the nearest end of the range.
Narrowing conversion
Converting to a type with fewer bits. The ordinary unsigned integer conversions shown keep low bits; a clamped typed-array store saturates instead.
Integer promotion
Conversion of lower-rank integer types to int when all their values fit, otherwise to unsigned int.
Undefined behaviour
A program state the standard gives no meaning, such as signed int overflow; no result is guaranteed.

Finite ranges and arithmetic policies

A fixed-width integer has a finite set of bit patterns. Signedness determines how those patterns represent values; overflow occurs when an arithmetic result exceeds the range of the type doing the calculation. A later conversion to a narrower type is another boundary, even when the calculation itself fit.

Choose the policy for the job: preserve a growing total, reject an out-of-range input, clamp it to a limit or deliberately wrap within a fixed width. The expression’s type, destination type and selected language’s rules determine what the program actually does. A wider destination cannot repair information already lost in an earlier operation.

01Signed and unsigned

The same eight bits have two readings

A retro-game save editor reads one byte of coins per stage. Its summary must add counts without losing coins, its checksum must follow the save format’s 32-bit rule, and its edits must leave valid byte counts. Start by checking how the selected language reads the stored bytes. Then separate the arithmetic used for each job.

The save format calls its coin field an unsigned byte. Before adding counts, check what happens if the editor reads that byte through a signed type. Eight bits give 256 patterns: an unsigned 8-bit type uses them for 0 to 255; a signed 8-bit type uses them for −128 to 127.

The program reads two bytes, 0xff and 0x80, first as unsigned values and then as signed ones. Predict the signed line.

On this target, <cstdint> supplies std::uint8_t and std::int8_t as aliases of unsigned char and signed char. Streams treat those as characters; unary + promotes them for numeric output. Exact-width aliases are optional on other implementations.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cstdint>
#include <iostream>

int main() {
    std::uint8_t high = 0xff;
    std::uint8_t top = 0x80;

    std::cout << +high << ' ' << +top << '\n';
    std::cout << +static_cast<std::int8_t>(high) << ' '
              << +static_cast<std::int8_t>(top) << '\n';
}
What does the signed line print?
C++ · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
clang++ -std=c++2c -Wall -Wextra -pedantic main.cpp -o main && ./main

Use the selected language’s setup from the first reading and replace the file for each experiment. Rust uses cargo run with the default dev profile and no overflow-check overrides. The Go target has 64-bit int. The C++ target has 8-bit bytes, 32-bit int and 64-bit std::size_t; its exact-width integer types are available. C++ uses the track’s C++26 mode; std::in_range needs C++20.

02One past the top

At the edge, arithmetic wraps, stops or widens

The summary must count one more coin after a stage reaches 255. Does the addition happen in the byte type, in a wider type, or only become a byte when stored? This small probe separates calculation from storage before the editor sums whole slots. Predict what the program prints.

level is a std::uint8_t at 255. auto takes the type of level + 1.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cstdint>
#include <iostream>

int main() {
    std::uint8_t level = 255;

    auto next = level + 1;
    level += 1;

    std::cout << next << ' ' << +level << '\n';
}
What does the program print?
Loading Across the eight-bit boundary…

03Narrowing

Check what an edited count stores

An edit can propose 300 coins or −20 coins even though neither fits the saved field. The program isolates the store from the addition. Does conversion refuse the proposal, stop at an endpoint, or produce another count? Predict the first line.

std::uint8_t stored = reading; is an implicit conversion. std::in_range (C++20, <utility>) asks whether a value fits a type.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cstdint>
#include <iostream>
#include <utility>

int main() {
    int reading = 300;
    int low = -20;

    std::uint8_t stored = reading;

    std::cout << +stored << '\n';
    std::cout << std::boolalpha << std::in_range<std::uint8_t>(reading) << '\n';
    std::cout << +static_cast<std::uint8_t>(low) << '\n';
}
What does the first line print?

04Choosing the width

The type of the arithmetic decides where it wraps

The save format defines its checksum modulo 2³². Making it wider like the coin total would change what is written to the save. This probe takes the largest unsigned 32-bit value and adds 1 using different arithmetic types. Predict where each result crosses its boundary.

hash is a std::uint32_t, and total a std::size_t initialized from it. The lab compiles for 64-bit Linux.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <limits>

int main() {
    std::uint32_t hash = std::numeric_limits<std::uint32_t>::max();
    std::size_t total = hash;

    ++hash;
    ++total;

    std::cout << hash << ' ' << total << '\n';
}
What does the program print?

05Repair the save editor

Totals, a 32-bit checksum, then clamped edits

One save editor for a retro game continues through three repairs. Each stage’s coin count is a byte. First report running totals that do not wrap. Then compute the save’s 32-bit checksum, which must wrap at exactly 32 bits. Finally apply signed edits that keep every count between 0 and 255.

The lab opens in your reading language and has its own language control. Each file contains its imports, types, reader and complete main. Later levels supply the earlier correct helpers.

Repair the save editor

A total wider than a byte, wrapping at exactly 32 bits, then a range that holds at both ends.

  1. easy · F-INT-V4-1 Total the coins
  2. medium · F-INT-V4-2 Keep the checksum to 32 bits
  3. hard · F-INT-V4-3 Clamp coin edits
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.