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';
}- 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