Clamping values with style


The following question was raised in one of our software devs channel at work:

On style and readability and intent : std::min or std::clamp or explicit if/reassign.

Option 1:

int x = someValue;
if (x > max) {
x = max;
}

Option 2:

int x = std::min(someValue, max);

Option 3:

int x = std::clamp(someValue, 0, max);

Option 3b:

int x = std::clamp(someValue, std::numeric_limits<int>::min(), max);

What’s best ?

Option 1 is explicit but does not show the intent.

Option 2 is a well known pattern although using min to limit the value to an upper bound is not very intuitive.

Option 3 is the most explicit but imposes to have both a lower and an upper bound. The original code had no explicit lower bound and 0 is actually not the native lower bound for int. So it is not strictly equivalent. Option 3b is the exact equivalent of the original code.

From the poll, option 2 was considered as the most natural although option 3 is even more readable.

I was wondering if there would be an impact on the generated assembly. In particular, the difference between Option 1 and the other options. So taking it to the test in godbolt.org.

Conclusion: as soon as the optimizer is enabled, Option 1, 2 and 3b are strictly the same. Option 3, quite naturally, involves an extra comparison since the lower bound is not the native lower bound of that type.

Share

Les commentaires sont fermés.