# std::clamp

> C++ Atlas: `cppatlas.com/w/cpp/algorithm/clamp` | Source: https://en.cppreference.com/w/cpp/algorithm/clamp | Domain: Algorithms | Standards: C++11, C++17, C++20

If the value of v is within [lo, hi], returns v; otherwise returns the nearest boundary.

## Official Specification Summary (cppreference)

```cpp
// Defined in header <algorithm>

template< class T >
constexpr const T& clamp( const T& v, const T& lo, const T& hi ); // (1) (since C++17)

template< class T, class Compare >
constexpr const T& clamp( const T& v, const T& lo, const T& hi,
                          Compare comp ); // (2) (since C++17)
```

If the value of `v` is within `[lo,` `hi]`, returns `v`; otherwise returns the nearest boundary.

1) Uses `operator<` (until C++20) `std::less{}` (since C++20) to compare the values.

If `T` is not *LessThanComparable*, the behavior is undefined.[1]

2) Uses the comparison function `comp` to compare the values.

If `lo` is greater than `hi`, the behavior is undefined.

1. ↑ If `NaN` is avoided, `T` can be a floating-point type.

### Parameters

- `v` - the value to clamp
- `lo, hi` - the boundaries to clamp `v` to
- `comp` - comparison function object (i.e. an object that satisfies the requirements of *Compare*) which returns `true` if the first argument is *less* than the second.

  The signature of the comparison function should be equivalent to the following:

  `bool cmp(const Type1& a, const Type2& b);`

  While the signature does not need to have `const&`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of value category (thus, `Type1&` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)).
  The types `Type1` and `Type2` must be such that an object of type `T` can be implicitly converted to both of them.

### Return value

Reference to `lo` if `v` is less than `lo`, reference to `hi` if `hi` is less than `v`, otherwise reference to `v`.

### Complexity

1) At most two comparisons using `operator<` (until C++20) `std::less{}` (since C++20).

2) At most two applications of the comparison function `comp`.

### Possible implementation

```cpp
template<class T>
constexpr const T& clamp(const T& v, const T& lo, const T& hi)
{
    return clamp(v, lo, hi, less{});
}
```

**clamp (2)**

```cpp
template<class T, class Compare>
constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp)
{
    return comp(v, lo) ? lo : comp(hi, v) ? hi : v;
}
```

### Notes

Capturing the result of

`std::clamp`

by reference produces a dangling reference if one of the parameters is a temporary and that parameter is returned:

```cpp
int n = -1;
const int& r = std::clamp(n, 0, 255); // r is dangling
```

If `v` compares equivalent to either bound, returns a reference to `v`, not the bound.

| Feature-test macro | Value | Std | Feature |
| --- | --- | --- | --- |
| `__cpp_lib_clamp` | `201603L` | (C++17) | `std::clamp` |

### Example

```cpp
#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>

int main()
{
    std::cout << "[raw] "
                 "[" << INT8_MIN << ',' << INT8_MAX << "] "
                 "[0," << UINT8_MAX << "]\n";

    for (const int v : {-129, -128, -1, 0, 42, 127, 128, 255, 256})
        std::cout << std::setw(4) << v
                  << std::setw(11) << std::clamp(v, INT8_MIN, INT8_MAX)
                  << std::setw(8) << std::clamp(v, 0, UINT8_MAX) << '\n';
}
```

Output:

```text
[raw] [-128,127] [0,255]
-129       -128       0
-128       -128       0
  -1         -1       0
   0          0       0
  42         42      42
 127        127     127
 128        127     128
 255        127     255
 256        127     255
```

### See also

- [`min`](https://en.cppreference.com/w/cpp/algorithm/min): returns the smaller of the given values (function template)
- [`max`](https://en.cppreference.com/w/cpp/algorithm/max): returns the greater of the given values (function template)
- [`in_range`](https://en.cppreference.com/w/cpp/utility/in_range) (C++20): checks if an integer value is in the range of a given integer type (function template)
- [`ranges::clamp`](https://en.cppreference.com/w/cpp/algorithm/ranges/clamp) (C++20): clamps a value between a pair of boundary values (algorithm function object)

---
Attribution: content from https://en.cppreference.com/w/cpp/algorithm/clamp (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.