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?
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.
If you live in the future, you can use
std::clamp
from C++17: