title: Do class/struct members always get created in memory in the order they were declared?
body: <p>This is a question that was sparked by <a href="https://stackoverflow.com/users/3631/rob-walker">Rob Walker</a>'s answer <a href="https://stackoverflow.com/questions/36455/alignment-restrictions-for-mallocfree#36466">here</a>.</p>
  <p>Suppose I declare a class/struct like so:</p>
  <pre><code>struct
  { 
      char A;
      int B;
      char C;
      int D;
  };
  </code></pre>
  <p>Is it safe to assume that these members will be declared in exactly that order in memory, or is this a compiler dependent thing?  I'm asking because I had always assumed that the compiler can do whatever it wants with them.</p>
  <p>This leads into my next question.  If the above example causes memory alignment issues, why can the compiler not just turn that into something like this implicitly:</p>
  <pre><code>struct
  { 
      char A;
      char C;
      int B;
      int D;
  };
  </code></pre>
  <p>(I'm primarily asking about C++, but I'd be interested to hear the C answer as well)</p>
  <h3>Related topics</h3>
  <ul>
  <li><a href="https://stackoverflow.com/questions/118068/why-doesnt-gcc-optimize-structs">Why doesn't GCC optimize structs?</a></li>
  </ul>