Dmytro
Dmytro

Reputation: 108

.NET CLI: How is a local variable popped off the stack if not on top?

I'm trying to figure out how Stack and Heap work.

So my question about Stack. For example, we have next code:

static void Main()
{
    int a = 1;
    int b = 2;

    Console.WriteLine(a);
}

Both variables will be pushed onto the stack, and variable 'b' will on top of variable 'a'.

If Stack has only Push and Pop operations, how variable 'a' can be read, without popping from stack 'b'?

Upvotes: 1

Views: 108

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062915

Local variables are defined before the dynamic / flexible part of the stack, so what you actually have is (assuming no optimisations):

  • define a & b in the stack-frame
  • push 1 onto the dynamic stack (after a & b)
  • write (pop) the value at the top of the stack into the location of a
  • push 2 onto the dynamic stack
  • write (pop) the value at the top of the stack into the location of b
  • load (push) the value from the location of a onto the dynamic stack
  • call Console.WriteLine

Local variable values can be accessed at any time; they are just relative offsets from the stack frame. The dynamic part of the stack used for transient values can only usually be accessed in strict order, but that isn't what contains the locations we're naming a and b.

Upvotes: 4

PMF
PMF

Reputation: 17248

You've got a misunderstanding here. Both a and b are put into the same stack frame, as they belong to the same method. Within main it is always known that a is at address Stackpointer + 8 and b at Stackpointer + 4 (for instance). For the execution stack, each method call is one stack frame (containing all local variables of a method). This is different from the Stack class, which contains one value per slot.

Upvotes: 2

Related Questions