How could I implement logical implication with bitwise or other efficient code in C?

前端 未结 5 2183
误落风尘
误落风尘 2021-02-20 18:01

I want to implement a logical operation that works as efficient as possible. I need this truth table:

p    q    p → q
T    T      T
T    F      F
F    T      T
F         


        
5条回答
  •  臣服心动
    2021-02-20 18:29

    FYI, with gcc-4.3.3:

    int foo(int a, int b) { return !a || b; }
    int bar(int a, int b) { return ~a | b; }
    

    Gives (from objdump -d):

    0000000000000000 :
       0:   85 ff                   test   %edi,%edi
       2:   0f 94 c2                sete   %dl
       5:   85 f6                   test   %esi,%esi
       7:   0f 95 c0                setne  %al
       a:   09 d0                   or     %edx,%eax
       c:   83 e0 01                and    $0x1,%eax
       f:   c3                      retq   
    
    0000000000000010 :
      10:   f7 d7                   not    %edi
      12:   09 fe                   or     %edi,%esi
      14:   89 f0                   mov    %esi,%eax
      16:   c3                      retq   
    

    So, no branches, but twice as many instructions.

    And even better, with _Bool (thanks @litb):

    _Bool baz(_Bool a, _Bool b) { return !a || b; }
    
    0000000000000020 :
      20:   40 84 ff                test   %dil,%dil
      23:   b8 01 00 00 00          mov    $0x1,%eax
      28:   0f 45 c6                cmovne %esi,%eax
      2b:   c3                      retq   
    

    So, using _Bool instead of int is a good idea.

    Since I'm updating today, I've confirmed gcc 8.2.0 produces similar, though not identical, results for _Bool:

    0000000000000020 :
      20:   83 f7 01                xor    $0x1,%edi
      23:   89 f8                   mov    %edi,%eax
      25:   09 f0                   or     %esi,%eax
      27:   c3                      retq   
    

提交回复
热议问题