Note that there are some explanatory texts on larger screens.

plurals
  1. POWhich is faster : if (bool) or if(int)?
    text
    copied!<blockquote> <p><a href="https://stackoverflow.com/questions/5554725/which-value-is-better-to-use-boolean-true-or-integer-1">Which value is better to use? Boolean true or Integer 1?</a></p> </blockquote> <p>The above topic made me do some experiments with <code>bool</code> and <code>int</code> in <code>if</code> condition. So just out of curiosity I wrote this program:</p> <pre><code>int f(int i) { if ( i ) return 99; //if(int) else return -99; } int g(bool b) { if ( b ) return 99; //if(bool) else return -99; } int main(){} </code></pre> <p><code>g++ intbool.cpp -S</code> generates asm code for each functions as follows:</p> <ul> <li><p>asm code for <code>f(int)</code></p> <pre><code>__Z1fi: LFB0: pushl %ebp LCFI0: movl %esp, %ebp LCFI1: cmpl $0, 8(%ebp) je L2 movl $99, %eax jmp L3 L2: movl $-99, %eax L3: leave LCFI2: ret </code></pre></li> <li><p>asm code for <code>g(bool)</code></p> <pre><code>__Z1gb: LFB1: pushl %ebp LCFI3: movl %esp, %ebp LCFI4: subl $4, %esp LCFI5: movl 8(%ebp), %eax movb %al, -4(%ebp) cmpb $0, -4(%ebp) je L5 movl $99, %eax jmp L6 L5: movl $-99, %eax L6: leave LCFI6: ret </code></pre></li> </ul> <p>Surprisingly, <code>g(bool)</code> generates more <code>asm</code> instructions! Does it mean that <code>if(bool)</code> is little slower than <code>if(int)</code>? I used to think <code>bool</code> is especially designed to be used in conditional statement such as <code>if</code>, so I was expecting <code>g(bool)</code> to generate less asm instructions, thereby making <code>g(bool)</code> more efficient and fast. </p> <p>EDIT:</p> <p>I'm not using any optimization flag as of now. But even absence of it, why does it generate more asm for <code>g(bool)</code> is a question for which I'm looking for a reasonable answer. I should also tell you that <code>-O2</code> optimization flag generates exactly same asm. But that isn't the question. The question is what I've asked.</p> <hr>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload