Search code examples
if-statementlanguage-agnostic

Branching without if statement


Is it possible to branch code without using an if statement?


Solution

  • Yes, you can, GPU-style.

    Say you have a function that branches, and returns a value at the end.

    float function( float input )
    {
        if( input > 0 )
        {
            // do stuff
            finalValue = 2+4+8*input;
            return finalValue ;
        }
        else
        {
            // do other stuff
            finalValue = 1+input;
            return finalValue ;
        }
    }
    

    To do this without branching, you can write the code GPU-style: that is, evaluate both branches, then throw away the one you don't want at the end.

    float function( float input )
    {
        // do stuff..regardless
        finalValue1 = 2+4+8*input;
    
        // do other stuff..regardless
        finalValue2 = 1+input;
    
        bool resultMask = input > 0 ; // 1 if should use finalValue1.
        return finalValue1*resultMask   +   finalValue2*(1 - resultMask) ;
    }
    

    So there you have it. Branching without branching, if statements without if statementing.