title: C++ CPU Register Usage
body: <p>In C++, local variables are always allocated on the stack. The stack is a part of the allowed memory that your application can occupy. That memory is kept in your RAM (if not swapped out to disk). Now, does a C++ compiler always create assembler code that stores local variables on the stack?</p>
  
  <p>Take, for example, the following simple code:</p>
  
  <pre><code>int foo( int n ) {
     return ++n;
  }
  </code></pre>
  
  <p>In MIPS assembler code, this could look like this:</p>
  
  <pre><code>foo:
  addi $v0, $a0, 1
  jr $ra
  </code></pre>
  
  <p>As you can see, I didn't need to use the stack at all for n. Would the C++ compiler recognize that, and directly use the CPU's registers?</p>
  
  <p><strong>Edit:</strong> Wow, thanks a lot for your almost immediate and extensive answers! The function body of foo should of course be <code>return ++n;</code>, not <code>return n++;</code>. :)</p>