Limit integer to bounds

1.3k views Asked by At

I'm trying to make sure that int x is greater or equal than 0 but smaller than 1080 (screen size in this case).

I came up with this

int x = 123;
x = std::min(std::max(x, 0), 1080);

This seems ugly. Is there a better way to achieve this?

4

There are 4 answers

3
melpomene On BEST ANSWER

If you live in the future, you can use std::clamp from C++17:

x = std::clamp(x, 0, 1080);
1
Bathsheba On

Use an unsigned as the type for x. That automatically constrains it to be non-negative.

Then you're left with just the call to std::min which is palatable to me at least.

Building a class that takes an int on construction and has a conversion operator to int is also plausible but requires a fair bit of boilerplate.

3
Spencer D On

Why not just do something like this?

int x = 123; /* Or some arbitrary number */
bool bIsInRange = (x >= 0) && (x < 1080);
if(!bIsInRange){
   std::cout << "Variable 'x' is not between 0 and 1080." << std::endl;
   return 1;
} // else, x is fine. Continue operations as normal.
2
Nick On

Naive solution looks ok too:

int x = 123;
if (x < 0)
    x = 0;
if (x > 1080)
    x = 1080;

or wrap everything in a function:

template<typename T>
T between(const T x, const T min, const T max){
   if (x < min)
       return min;

   if (x > max)
       return max;

   return x;
}

int x = between(123, 0, 1080);