Reputation: 108
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
Reputation: 1062915
Local variables are defined before the dynamic / flexible part of the stack, so what you actually have is (assuming no optimisations):
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
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