问题描述:

int value;

  1. if (value % 2) {...}
  2. if (value % 2 != 0) {...}

I do know the second is more easily readable, but which one is more efficient in C, 1 or 2? And why?

网友答案:

They are the exact same. Any condition in an if statement is tested wether it is true (non-zero) or false (zero), so even if you don't write out the test against zero the generated code does that test for you.

From the C11 standard:

6.8.4.1 The if statement:

[...]In both forms, the first substatement is executed if the expression compares unequal to 0.

Edit: You can also verify this for your compiler by looking at the generated code. In my case (GCC 2.4.9) both of the forms produce this code:

    movl    -4(%rbp), %eax  ; Load `value` into eax
    andl    $1, %eax        ; % 2 (same as & 1)
    testl   %eax, %eax      ; is it zero?
    je  .L2                 ; yes, jump

I compiled with no optimization (-O0), just to get that out of the way.

网友答案:

The first is in view of performance (depending on compiler, because it is suggestable that any known compiler would be able to detect and optimize it anyway) the better one as the second one simply executes an additional comparrison.

相关阅读:
Top