There are many ways to implement abs()
with or without branching. I came across this one:
r = (v < 0) ? -(unsigned)v : v;
Does this use branching or is it branchless?
And why can it not just use -v
, instead of -(unsigned)v
? What does the (unsigned)
do here? Why does it give more correct results than -v
?
r=(v<0)?-(unsigned)v : v
There are some ways to compute abs
without branching but this one is not one of them as <
and ?:
operators are usually translated to branching instructions.
Assuming r
is of type unsigned int
, the cast to unsigned
is here to get a specified behavior when v
value is INT_MIN
. Without the cast, -v
would be undefined behavior when v
is INT_MIN
(as -INT_MIN
is undefined behavior in C).