c++mipsbranchless

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


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.


Solution

  • 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