title: Structure alignment in Visual C++
body: <p>Visual C++ offers both a compiler switch (<code>/Zp</code>) and the <code>pack</code> pragma to affect the aligment of struct members. However, I seem to have some misconception as to how they work.</p>
  
  <p>According to <a href="http://msdn.microsoft.com/en-us/library/2e70t5y1.aspx" rel="noreferrer">MSDN</a>, for a given alignment value n,</p>
  
  <blockquote>
    <p>The alignment of a member will be on a boundary that is either a
    multiple of n or a multiple of the size of the member, whichever is
    smaller.</p>
  </blockquote>
  
  <p>Let's assume a pack value of 8 bytes (which is the default). Within a struct, I'd think that any member whose size is less than 8 bytes will be at an offset that is a multiple of its own size. Any member whose size is 8 bytes or more will be at an offset that is a multiple of 8 bytes.</p>
  
  <p>Now take the following program:</p>
  
  <pre><code>#include &lt;tchar.h&gt;
  
  #pragma pack(8)
  
  struct Foo {
      int i1;
      int i2;
      char c;
  };
  
  struct Bar {
      char c;
      Foo foo;
  };
  
  int _tmain(int argc, _TCHAR* argv[]) {
      int fooSize = sizeof(Foo); // yields 12
      Bar bar;
      int fooOffset = ((int) &amp;bar.foo) - ((int) &amp;bar); // yields 4
  
      return 0;
  }
  </code></pre>
  
  <p>The <code>Foo</code> structure is 12 bytes in size. So within <code>Bar</code>, I'd expect the <code>Foo</code> member to be at offset 8 (a multiple of 8) while actually it's at offset 4. Why is that?</p>
  
  <p>Also, <code>Foo</code> really only has 4+4+1 = 9 bytes of data. The compiler automatically adds padding bytes at the end. But again, given an alignment value of 8 bytes, shouldn't it pad to a multiple of 8 rather than 4?</p>
  
  <p>Any clarification appreciated!</p>