Why is there no clamp function in math.h
Perhaps because:
double clamp(double x, double upper, double lower)
{
return min(upper, max(x, lower));
}
uses fewer characters than your question.
An alternative type-free method is
#define CLAMP(x, upper, lower) (MIN(upper, MAX(x, lower)))
assuming you have MIN
and MAX
macros in the normal form.
A templated C++ version could be implemented as follows:
template<class T>
const T& clamp(const T& x, const T& upper, const T& lower) {
return min(upper, max(x, lower));
}
Naturally, the latter will not work in good ol' C.
To be more constructive, the function isn't in the standard library because the authors did not feel the need for it to be there sufficiently to add it. It's pretty obvious how to achieve the function you want (see above), so there's no particular hardship. Once you have a standard for what's in the library, adding further functions risks namespace collisions with existing code, requires documentation, testing etc., so there is a threshold of general usefulness any new function needs to cross.
The other answers are no longer valid, as std::clamp is now in C++17.
At the time of writing it isn't supported by GCC, but will be in GCC 7.