Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The difference is that with <code>#define</code> or <code>enum</code> the value 3 doesn't need to exist as an explicit value in the code and so the compiler has decided to use two add instructions rather than allocating space for the constant 3. The <code>add reg,reg</code> instruction is 2 bytes per instruction, so thats 6 bytes of instructions and 0 bytes for constants to multiply by 3, that's smaller code than <code>imul</code> plus a 4 byte constant. Plus the way the add instructions are used, it works out to a pretty literal translation of *2 *3, so this may not be a size optimization, it may be the default compiler output whenever you multiply by 2 or by 3. (add is usually a faster instruction than multiply). </p> <p><code>#define</code> and <code>enum</code> don't declare an instance, they only provide a way to give a symbolic name to the value 3, so the compiler has the option of making smaller code. </p> <pre><code> mov $0x1, -0x4(%ebp) ; r=1 mov -0x4(%ebp), %edx ; edx = r mov %edx, %eax ; eax = edx add %eax, %eax ; *2 add %edx, %eax ; add %eax, %eax ; *3 mov %eax, -0x8(%ebp) ; a = eax </code></pre> <p>But when you declare <code>const int pi = 3</code>, you tell the compiler to allocate space for an integer value and initialize it with 3. That uses 4 bytes, but the constant is now available to use as an operand for the <code>imul</code> instruction. </p> <pre><code> movl $0x3, -0x8(%ebp) ; pi = 3 movl $0x3, -0x4(%ebp) ; r = 3? (typo?) mov -0x4(%ebp), %eax ; eax = r add %eax, %eax ; *2 imul -0x8(%ebp), %eax ; *pi mov %eax, 0xc(%ebp) ; a = eax </code></pre> <p>By the way, this is clearly not optimized code. Because the value <code>a</code> is never used, so if optimization were turned on, the compiler would just execute </p> <pre><code>xor eax, eax ; return 0 </code></pre> <p>In all 3 cases.</p> <h1>Addendum:</h1> <p>I tried this with MSVC and in debug mode I get the same output for all 3 cases, MSVC always uses imul by a literal 6. Even in case 3 when it creates the <code>const int = 3</code> it doesn't actually reference it in the imul. </p> <p>I don't think this test really tells you anything about const vs define vs enum because this is non-optimized code. </p>
 

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