Pavel Oganesyan
Pavel Oganesyan

Reputation: 6924

Nice way to make a limit to the value

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?

Upvotes: 0

Views: 87

Answers (5)

Science_Fiction
Science_Fiction

Reputation: 3433

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.

Upvotes: 0

user1653241
user1653241

Reputation:

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

Upvotes: 0

Vinayak Garg
Vinayak Garg

Reputation: 6616

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

Upvotes: 1

weltensturm
weltensturm

Reputation: 2162

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.

Upvotes: 0

Minion91
Minion91

Reputation: 1929

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.

Upvotes: 2

Related Questions