不使用 if 语句进行分支

bob*_*obo 3 language-agnostic if-statement

是否可以在不使用if语句的情况下分支代码?

bob*_*obo 5

是的,可以,GPU 风格。

假设您有一个分支函数,并在最后返回一个值。

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 ;
    }
}
Run Code Online (Sandbox Code Playgroud)

要在不分支的情况下执行此操作,您可以编写 GPU 风格的代码:即评估两个分支,然后在最后丢弃您不想要的分支

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) ;
}
Run Code Online (Sandbox Code Playgroud)

所以你有它。没有分支的分支,没有 if 语句的 if 语句。