Skip to content
C++ Basics: Find an Integer Midpoint Without Overflow

C++ Basics: Find an Integer Midpoint Without Overflow

November 5, 2026

Use std::midpoint for large integer endpoints and make its rounding direction explicit.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as midpoint-overflow-rounding-demo.cpp:

#include <iostream>
#include <limits>
#include <numeric>

int main()
{
    const int high = std::numeric_limits<int>::max();
    std::cout << "Near maximum: " << std::boolalpha
              << (std::midpoint(high - 2, high) == high - 1) << '\n';
    std::cout << "2 to 5: " << std::midpoint(2, 5) << '\n';
    std::cout << "5 to 2: " << std::midpoint(5, 2) << '\n';
}

Compile and run it. The program runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic midpoint-overflow-rounding-demo.cpp -o midpoint-overflow-rounding-demo &&
./midpoint-overflow-rounding-demo

Observed output:

Near maximum: true
2 to 5: 3
5 to 2: 4

Read the result

The near-maximum check succeeds without adding two large endpoints directly. For the odd sum of 2 and 5, the answer rounds toward the first argument: reversing the arguments changes the answer from 3 to 4.

Apply it carefully

For signed integers, (a + b) / 2 can overflow before division. std::midpoint avoids that overflow. Its arguments must deduce the same arithmetic type, excluding bool. Decide which rounding direction your interval algorithm needs; exchanging endpoints is observable for an odd integer sum. This example uses the arithmetic overload, not pointer arithmetic.

The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.

Clean up

Remove only the source and executable created here, then return to the starting directory:

rm -- midpoint-overflow-rounding-demo.cpp midpoint-overflow-rounding-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on