C Ternary Operation without Conditional Statement

From Software Engineers Wiki
Jump to: navigation, search

Consider a statement with a ternary operator: result = a ? b : c; Implement this without using conditional statement.

Answer

If a is non-zero, !a = 0. !!a = 1. If a is zero, !a = 1, !!a = 0.

result = (!!a * b) + (!a * c);

People may think that conditional operator may cause a branch which is costly, this trick may avoid branching. However, many architectures implement conditional instructions which do not branch at all. Also multiplication is also expensive instruction. In short, avoid this trick.

For following codes,

int ternary_operator(int a, int b, int c)
{
        return a ? b : c;
}

int ternary_without_operator(int a, int b, int c)
{
        return (!!a * b) + (!a * c);
}

gcc for x86

0000000000000000 <ternary_operator>:
   0:   89 f0                   mov    %esi,%eax
   2:   85 ff                   test   %edi,%edi
   4:   0f 44 c2                cmove  %edx,%eax
   7:   c3                      retq

0000000000000010 <ternary_without_operator>:
  10:   31 c9                   xor    %ecx,%ecx
  12:   85 ff                   test   %edi,%edi
  14:   0f 95 c1                setne  %cl
  17:   31 c0                   xor    %eax,%eax
  19:   0f af ce                imul   %esi,%ecx
  1c:   85 ff                   test   %edi,%edi
  1e:   0f 94 c0                sete   %al
  21:   0f af c2                imul   %edx,%eax
  24:   01 c8                   add    %ecx,%eax
  26:   c3                      retq

gcc for ARM

00000000 <ternary_operator>:
   0:   e3500000        cmp     r0, #0
   4:   11a00001        movne   r0, r1
   8:   01a00002        moveq   r0, r2
   c:   e12fff1e        bx      lr

00000010 <ternary_without_operator>:
  10:   e3500000        cmp     r0, #0
  14:   11a00001        movne   r0, r1
  18:   01a00002        moveq   r0, r2
  1c:   e12fff1e        bx      lr
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox