Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid branching in C for this operation

Is there a way to remove the following if-statement to check if the value is below 0?

int a = 100;
int b = 200;
int c = a - b;

if (c < 0)
{
    c += 3600;
}

The value of c should lie between 0 and 3600. Both a and b are signed. The value of a also should lie between 0 and 3600. (yes, it is a counting value in 0.1 degrees). The value gets reset by an interrupt to 3600, but if that interrupt comes too late it underflows, which is not of a problem, but the software should still be able to handle it. Which it does.

We do this if (c < 0) check at quite some places where we are calculating positions. (Calculating a new position etc.)

I was used to pythons modulo operator to use the signedness of the divisor where our compiler (C89) is using the dividend signedness.

Is there some way to do this calculation differently? example results:

 a  -  b  = c
100 - 200 = 3500  
200 - 100 = 100
like image 441
Daan Timmer Avatar asked Jul 19 '13 14:07

Daan Timmer


1 Answers

Good question! How about this?

c += 3600 * (c < 0);

This is one way we preserve branch predictor slots.

like image 149
jman Avatar answered Sep 25 '22 02:09

jman