Limit integer to bounds [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-01 09:41:00

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

x = std::clamp(x, 0, 1080);

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);

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.

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.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!