bhylu.com

Advertisements

C++ Integer Overflow

Guard an integer addition using a precondition that cannot overflow while being checked.

How it works

A public count operation needs a policy for negative values and values beyond its representation. Checking a result after signed overflow is too late because the evaluation already has undefined behaviour. For nonnegative operands, compare the increment against the maximum minus the current count before addition. This helper returns an optional result: absence means the requested nonnegative total cannot be represented. A general signed arithmetic function needs a different check for negative increments.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror checked-arithmetic.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · checked-arithmetic.cpp

#include <iostream>
#include <optional>
#include <limits>

std::optional<int> add_count(int current, int extra) {
    if (current < 0 || extra < 0 || current > std::numeric_limits<int>::max() - extra) { return std::nullopt; }
    return current + extra;
}

int main() {
    auto total = add_count(12, 8);
    if (total) { std::cout << "Total: " << *total << '\n'; }
    std::cout << "Overflow rejected: " << !add_count(std::numeric_limits<int>::max(), 1).has_value() << '\n';
}

Expected result

Total: 20
Overflow rejected: 1

Short-circuit evaluation prevents the subtraction from being used under an invalid negative-extra assumption. The optional carries an int only on success. The caller checks presence before dereferencing it. This makes a legitimate zero distinct from failure and keeps the original operands unchanged when a request is rejected.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.