title: Bit-fields at two separate locations in a Structure in C
body: <p>In a structure we normally have contiguous bit-fields; that is, one after the other and adjacent to each other — for example:</p>
  
  <pre><code>struct demo
  {
    char a;
    char b:1;
    char c:2;
    char d:2;
    int  e;  
  } demo1;
  </code></pre>
  
  <p>The size of <code>demo1</code> will be 8 bytes:</p>
  
  <ul>
  <li>size = <code>a</code>(1 byte) + bit-fields(1 byte) + gap(2 bytes) + <code>e</code>(4 bytes))</li>
  </ul>
  
  <p>Now consider following structure:</p>
  
  <pre><code>struct demo
  {
    char a;
    int  b:1;
    char c;
    char d;
    int  e:2;
  } demo1;
  </code></pre>
  
  <p>When I use <code>sizeof(demo1)</code>, it gives me 8 bytes — but I want to know how these bit-fields are presented in memory.</p>
  
  <p>If calculated like above structure size should be:</p>
  
  <ul>
  <li>size = <code>a</code>(1 byte) + <code>b</code>(4 bytes) + <code>c</code>(1 byte) + <code>d</code>(1 byte) + <code>e</code>(4 bytes)</li>
  </ul>
  
  <p>During programming we don't bother about this thing that how size will be calculated using <code>sizeof</code> and we even don't use bit-fields at two different locations, but sometimes this type of question is asked by interviewers.</p>