title: How exactly does the callstack work?
body: <p>I'm trying to get a deeper understanding of how the low level operations of programming languages work and especially how they interact with the OS/CPU. I've probably read every answer in every stack/heap related thread here on Stack&nbsp;Overflow, and they are all brilliant. But there is still one thing that I didn't fully understand yet.</p>
  
  <p>Consider this function in pseudo code which tends to be valid Rust code ;-)</p>
  
  <pre><code>fn foo() {
      let a = 1;
      let b = 2;
      let c = 3;
      let d = 4;
  
      // line X
  
      doSomething(a, b);
      doAnotherThing(c, d);
  }
  </code></pre>
  
  <p>This is how I assume the stack to look like on line X:</p>
  
  <pre><code>Stack
  
  a +-------------+
    | 1           | 
  b +-------------+     
    | 2           |  
  c +-------------+
    | 3           | 
  d +-------------+     
    | 4           | 
    +-------------+ 
  </code></pre>
  
  <p>Now, everything I've read about how the stack works is that it strictly obeys LIFO rules (last in, first out). Just like a stack datatype in .NET, Java or any other programming language.</p>
  
  <p>But if that's the case, then what happens after line X? Because obviously, the next thing we need is to work with <code>a</code> and <code>b</code>, but that would mean that the OS/CPU (?) has to pop out <code>d</code> and <code>c</code> first to get back to <code>a</code> and <code>b</code>. But then it would shoot itself in the foot, because it needs <code>c</code> and <code>d</code> in the next line.</p>
  
  <p>So, I wonder what <strong>exactly</strong> happens behind the scenes?</p>
  
  <p>Another related question. Consider we pass a reference to one of the other functions like this:</p>
  
  <pre><code>fn foo() {
      let a = 1;
      let b = 2;
      let c = 3;
      let d = 4;
  
      // line X
  
      doSomething(&amp;a, &amp;b);
      doAnotherThing(c, d);
  }
  </code></pre>
  
  <p>From how I understand things, this would mean that the parameters in <code>doSomething</code> are essentially pointing to the same memory address like <code>a</code> and <code>b</code> in <code>foo</code>. But then again this means that there is no <em>pop up the stack until we get to <code>a</code> and <code>b</code></em> happening.</p>
  
  <p>Those two cases make me think that I haven't fully grasped how <strong>exactly</strong> the stack works and how it strictly follows the <em>LIFO</em> rules.</p>