Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit integer to bounds [duplicate]

Tags:

c++

max

min

clamp

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?

like image 949
Eric Avatar asked Sep 03 '26 08:09

Eric


1 Answers

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

x = std::clamp(x, 0, 1080);
like image 67
melpomene Avatar answered Sep 05 '26 23:09

melpomene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!