title: C++ Unions bit fields task
body: <p>Can somebody clear me out why would I use union and with what purpose the same address for the cin'ed variable and bit field (task from the Schildts C++ book)? In other words why would I use union for : </p>
  
  <blockquote>
    <p>char ch;
     struct byte bit;</p>
  </blockquote>
  
  <p>// Display the ASCII code in binary for characters.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;conio.h&gt;
  using namespace std;
  
  // a bit field that will be decoded
  struct byte {
    unsigned a : 1;
    unsigned b : 1;
    unsigned c : 1;
    unsigned d : 1;
    unsigned e : 1;
    unsigned f : 1;
    unsigned g : 1;
    unsigned h : 1;
  };
  
  union bits {
    char ch;
    struct byte bit;
  } ascii ;
  
  void disp_bits(bits b);
  
  int main()
  {
    do {
      cin &gt;&gt; ascii.ch;
      cout &lt;&lt; ": ";
      disp_bits(ascii);
    } while(ascii.ch!='q'); // quit if q typed
  
    return 0;
  }
  
  // Display the bit pattern for each character.
  void disp_bits(bits b)
  {
    if(b.bit.h) cout &lt;&lt; "1 ";
      else cout &lt;&lt; "0 ";
    if(b.bit.g) cout &lt;&lt; "1 ";
      else cout &lt;&lt; "0 ";
    if(b.bit.f) cout &lt;&lt; "1 ";
      else cout &lt;&lt; "0 ";
    if(b.bit.e) cout &lt;&lt; "1 ";
      else cout &lt;&lt; "0 ";
    if(b.bit.d) cout &lt;&lt; "1 ";
      else cout &lt;&lt; "0 ";
    if(b.bit.c) cout &lt;&lt; "1 ";
      else cout &lt;&lt; "0 ";
    if(b.bit.b) cout &lt;&lt; "1 ";
      else cout &lt;&lt; "0 ";
    if(b.bit.a) cout &lt;&lt; "1 ";
      else cout &lt;&lt; "0 ";
    cout &lt;&lt; "\n";
  }
  </code></pre>