Codectionary / Developer documentation / C++

C++ std::clamp bounds

C++17 clamp returns a value bounded by a lower and upper limit. It is useful for UI ranges and numeric controls when the bounds are ordered.

Syntax

auto bounded = std::clamp(value, low, high);

Examples

C++ std::clamp bounds

Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.

#include <algorithm>
#include <iostream>
int main() {
    int requested = 140;
    int percent = std::clamp(requested, 0, 100);
    std::cout << percent << '\n';
}
  1. Output: 100. A value within the interval would remain unchanged.

Best practices

  • Ensure low <= high. Store the result by value when limits are temporaries because clamp returns a reference.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading