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::clamp

Use case

Bound values to valid ranges.

Explanation

std::clamp(v, lo, hi) returns v bounded to [lo, hi].

Code

#include <algorithm>
#include <cstdint>
#include <iostream>

int main() {
  uint64_t offset = 0x5000;
  uint64_t minOff = 0x1000;
  uint64_t maxOff = 0x4000;

  auto bounded = std::clamp(offset, minOff, maxOff);

  std::cout << "Clamped: 0x" << std::hex << bounded << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++17/build/std-clamp
Clamped: 0x4000