ccomparisonbranchless

Double or set integer without branching in C


I want to write a function that when called doubles its argument (if it is non-zero) or returns a specific constant (if it is zero). The constant is always a power of 2 if that helps.

Let's say the constant is 8. When called with 0, I want it to return 8. When called with 8, I want it to return 16. And so on.

The trivial approach would be something like:

unsigned foo(unsigned value)
{
    return (value ? value * 2 : 8);
}

Is it possible to do this without branching?


Solution

  • This causes no additional memory access.

    int f(int a)
    {
        const int c = 8;
        return (a*2)+(a==0)*c;
    }