title: Can a C compiler rearrange stack variables?
body: <p>I have worked on projects for embedded systems in the past where we have rearranged the order of declaration of stack variables to decrease the size of the resulting executable.  For instance, if we had:</p>
  
  <pre><code>void func()
  {
      char c;
      int i;
      short s;
      ...
  }
  </code></pre>
  
  <p>We would reorder this to be:</p>
  
  <pre><code>void func()
  {
      int i;
      short s;
      char c;
      ...
  }
  </code></pre>
  
  <p>Because of alignment issues the first one resulted in 12 bytes of stack space being used and the second one resulted in only 8 bytes.</p>
  
  <p>Is this standard behavior for C compilers or just a shortcoming of the compiler we were using?  </p>
  
  <p>It seems to me that a compiler should be able to reorder stack variables to favor smaller executable size if it wanted to.  It has been suggested to me that some aspect of the C standard prevents this, but I haven't been able to find a reputable source either way.</p>
  
  <p>As a bonus question, does this also apply to C++ compilers?</p>
  
  <p><strong>Edit</strong></p>
  
  <p>If the answer is yes, C/C++ compilers can rearrange stack variables, can you give an example of a compiler that definitely does this?  I'd like to see compiler documentation or something similar that backs this up.</p>
  
  <p><strong>Edit Again</strong></p>
  
  <p>Thanks everybody for your help.  For documentation, the best thing I've been able to find is the paper <a href="http://mirror-fpt-telecom.fpt.net/gcc/summit/2003/Optimal%20Stack%20Slot%20Assignment.pdf" rel="noreferrer">Optimal Stack Slot Assignment in GCC</a>(pdf), by Naveen Sharma and Sanjiv Kumar Gupta, which was presented at the GCC summit proceedings in 2003.</p>
  
  <p>The project in question here was using the ADS compiler for ARM development.  It is mentioned in the documentation for that compiler that ordering declarations like I've shown can improve performance, as well as stack size, because of how the ARM-Thumb architecture calculates addresses in the local stack frame.  That compiler didn't automatically rearrange locals to take advantage of this.  The paper linked here says that as of 2003 GCC also didn't rearrange the stack frame to improve locality of reference for ARM-Thumb processors, but it implies that you could.</p>
  
  <p>I can't find anything that definitely says this was ever implemented in GCC, but I think this paper counts as proof that you're all correct.  Thanks again.</p>