Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::midpoint

Use case

Calculate midpoint without overflow.

Explanation

(a * b) / 2 can overflow. std::midpoint handles this correctly.

Code

#include <cstdint>
#include <iostream>
#include <numeric>

int main() {
  uint64_t start = 0x10000000;
  uint64_t end = 0x10001000;

  uint64_t mid = std::midpoint(start, end);

  std::cout << "Range: 0x" << std::hex << start << " - 0x" << end << "\n";
  std::cout << "Midpoint: 0x" << mid << "\n";
  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/std-midpoint
Range: 0x10000000 - 0x10001000
Midpoint: 0x10000800