Question

I have a code with pixel brightness that is limited to [0..255]. And it's evaluated for some reason, so I can get value outside the bounds. I can do

(if x>maxValue) x = maxValue;

or

 x = min(x, MaxValue);

or

(x > MaxValue) ? MaxValue : x;

but I wonder what is the nice way? How to limit a value with less comparisons and with good code style?

Was it helpful?

Solution

How to limit a value with less comparisons and with good code style?

One comparison is least, any lesser means there is no comparison. Look at Compute minimum without branching, if you want this.

For good style, this is best -

if (x > maxValue)
{
    x = maxValue;
}

OTHER TIPS

Use an unsigned char instead of an int for x, chars are limited to [0, 255]. This is a little bit tricky though as you have to check for overflow.

inline long clamp(long x, long min, long max){
    return x>max ? max : (x<min ? min : x);
}

You could write a new class that only accepts values between 0 and 255, and can be implicitly casted to an int, but using something like clamp or max should suffice.

As far as good coding style, you could create your own class to manage this value bounding requirement. If you overload the assignment operator, you could do the comparison there.

Edit: I suppose you could just put all your code in one function instead. But I think interacting with a class instance would be better.

BoundedInt x;
x = 300;
x.value(); // x == 255

I would guess:

(x > MaxValue) ? MaxValue : x;

is equivalent to:

(if x>maxValue) x = maxValue;
else x = x;

I know chances are high that it will get optimized away etc, or stop at self assignment etc. So in essence it is the same as the first if, just syntax sugar coating.

I would use min since it will provide type safety, and help to avoid comparing mixed types.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top