Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><s>Honestly, who cares??</s></p> <p>[Edit:] This actually turned out somewhat interesting. Contrary to my initial assumption, in <em>unoptimized</em> compilation, <code>n += b;</code> is better than <code>n += b ? 1 : 0;</code>. However, with optimizations, the two are identical. More importantly, though, the optimized version of this form is always better than <code>if (b) ++n;</code>, which <em>always</em> creates a <code>cmp/je</code> instruction. [/Edit]</p> <p>If you're terribly curious, put the following code through your compiler and compare the resulting assembly! (Be sure to test various optimization settings.)</p> <pre><code>int n; void f(bool b) { n += b ? 1 : 0; } void g(bool b) { if (b) ++n; } </code></pre> <p>I tested it with GCC 4.6.1: With <code>g++</code> and with no optimization, <code>g()</code> is shorter. With <code>-O3</code>, however, <code>f()</code> is shorter:</p> <pre><code>g(): f(): cmpb $0, 4(%esp) movzbl 4(%esp), %eax je .L1 addl %eax, n addl $1, n .L1: rep </code></pre> <p>Note that the optimization for <code>f()</code> actually does what you wrote originally: It literally adds the value of the conditional to <code>n</code>. This is in C++ of course. It'd be interesting to see what the C compiler would do, absent a <code>bool</code> type.</p> <p>Another note, since you tagged this C as well: In C, if you don't use bools (from <code>&lt;stdbool.h&gt;</code>) but rather <code>int</code>s, then the advantage of one version over the other disappears, since both now have to do some sort of testing.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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