c++ - Which is faster for checking whether a condition is true? -


(1)

if (!cond) 

or

(2)

if (cond == false) 

seems see lot of people using (1). isn't less optimal? in c++, if (...) statement evaluates true long whatever in parentheses non-zero value. so, in (1), has happen is

  • do logical not on cond
  • check whether result non-zero (whether bits on)

whereas, in (2), has happen is

  • check whether cond 0 (whether bits off)

now, time taken check whether bits off greater or equal time check whether bits on. therefore, question whether time perform logical not makes difference, on average.

which should use optimize code?

tested clang -o3:

int main () {     int i;     cin >> i;      if (i == 0)     return -1; } 

produces

leaq    4(%rsp), %rsi movl    $_zst3cin, %edi callq   _znsirseri cmpl    $1, 4(%rsp) sbbl    %eax, %eax popq    %rdx ret 

while

int main () {     int i;     cin >> i;      if (!i)     return -1; } 

produces

leaq    4(%rsp), %rsi movl    $_zst3cin, %edi callq   _znsirseri cmpl    $1, 4(%rsp) sbbl    %eax, %eax popq    %rdx ret 

so no difference @ all.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -