title: problem representing a register with unions and bit fields
body: <p>I'm writing a NES emulator in C++, and I bumped into an issue using bit fields to represent a register, which caused a very nasty bug. I'm representing an internal address register as:</p>
  
  <pre><code>union
      {
          struct
          {
              uint16_t coarseX : 5;            // bit field type is uint16_t, same as reg type
              uint16_t coarseY : 5;
              uint16_t baseNametableAddressX : 1;
              uint16_t baseNametableAddressY : 1;
              uint16_t fineY : 3;
              uint16_t unused : 1;
          } bits;
          uint16_t reg;
      } addressT, addressV;   // temporary VRAM adddress register and VRAM address register
  </code></pre>
  
  <p>so I can access the single bit-fields, and the register as a whole.</p>
  
  <p>Initially I wrote the register as:</p>
  
  <pre><code>union
      {
          struct
          {
              uint8_t coarseX : 5;             // bit field type is uint8_t, reg type is uint16_t
              uint8_t coarseY : 5;
              uint8_t baseNametableAddressX : 1;
              uint8_t baseNametableAddressY : 1;
              uint8_t fineY : 3;
              uint8_t unused : 1;
          } bits;
          uint16_t reg;
      } addressT, addressV;   // temporary VRAM adddress register and VRAM address register
  </code></pre>
  
  <p>The bug was caused by the bit field behaviour when the type of the bit field (for example coarseX) is different from that of the register (reg). 
  In this case, when I increment a field (i.e. coarseX++), the reg member was updated "incorrectly", meaning that the bit pattern inside reg didn't reflect the pattern represented by the bit fields (or by the bit fields as I layed out them inside the struct).
  I know that the compiler can pack bit fields inside "allocation units", and may even insert padding, but why the behaviour changes when I change the type of the bit field?</p>
  
  <p>Can someone please explain why?</p>