Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to limit an integer value to a certain range without branching?

Tags:

Just out of curiosity. If I have something like:

if(x < 0)     x = 0; if(x > some_maximum)     x = some_maximum;  return x; 

Is there a way to not branch? This is c++.

Addendum: I mean no branch instructions in the assembly. It's a MIPS architecture.

like image 882
Matt Wamboldt Avatar asked May 19 '10 18:05

Matt Wamboldt


People also ask

How do you store integer values?

The INTEGER value is stored as a signed binary integer and is typically used to store counts, quantities, and so on. Arithmetic operations and sort comparisons are performed more efficiently on integer data than on float or decimal data. INTEGER columns, however, cannot store absolute values beyond (2 31-1).

How do you check if a value is between two numbers in C++?

I attempted using the boolean operator && to check the two < and > values if they were true, so that anything between the two numbers would activate the cout statement to print the appropriate message for the numerical value entered.


1 Answers

There are bit-tricks to find the minimum or maximum of two numbers, so you could use those to find min(max(x, 0), some_maximum). From here:

y ^ ((x ^ y) & -(x < y)); // min(x, y) x ^ ((x ^ y) & -(x < y)); // max(x, y) 

As the source states though, it's probably faster to do it the normal way, despite the branch

like image 86
Michael Mrozek Avatar answered Oct 04 '22 16:10

Michael Mrozek