openclsimdgpgpuconditional-operator

What is OpenCL's select operator useful for?


I've noticed that OpenCL has a select() function/builtin/operator, which seems to be similar to the ternary operator in C and C++, but not quite. What are the differences between select() and ?:, and why is the former even required if we have the latter?


Solution

  • The reason the select operator is necessary/useful is for working with OpenCL vector types, like int2, float4 etc. Unlike in C++, where you could overload various operators to give them custom semantics - in C (and OpenCL C) there's only the default behavior. For the ternary operator, that means that for

    x ? expression_for_true : expression_for_false
    

    a single check will be performed, and the single appropriate value will be used - even if all three operands are of an OpenCL vector type.

    Instead, with select():

    Also, to confuse us a bit, the order of parameters to select() is different than with the ternary operator: x ? y : z corresponds to select(z, y, x).

    Thus if

    x = (int4) ( 1, 0 );
    y = (float4) ( 1.2, 3.4 );
    z = (float4) ( 5.6, 7.8 );
    

    then

    select(z, y, x) == (float4) ( 1.2, 7.8 );
    

    See also the Khronos OpenCL documentation, here and here.