Hadrian
Hadrian

Reputation: 55

C# Change value of local variable - stack representation

I have a question about variables on stack in C#, look at example below:

static void Main(string[] args)
{
     int a = 1; //this element goes to the stack as the first one 
     int b = 2; //second element in the stack
     a = 4;
     a++;
}

How it's possible to change value of variable "a" without pop the variable "b" from stack ?

I will be grateful if someone explain me how it works in this case ?

Upvotes: 1

Views: 848

Answers (2)

yu_sha
yu_sha

Reputation: 4410

Local variables are indeed located on stack, but compiler hides the stack from you. Basically, it translates your variables into addresses relative to the top of the stack. In your example, compiler knows that b is the last thing on the stack, and a one before last.

When a function is executed, one register (SP on classic 8086 processor, now it's probably ESP or something) points to the address at the top of the stack. Function arguments and local variables are addressed as [SP+n], where n is the number of bytes from top of the stack.

Upvotes: 0

decPL
decPL

Reputation: 5402

The memory construct that .NET uses to hold value types is indeed called 'the stack', but it doesn't mean that each and every variable is held in a LIFO structure, where you can only access the last one.

So to answer your question - when you need to access the variable a - CLR does that exactly (i.e. accesses it directly), there's no need to pop anything here.

You can read more about it, for example, here: http://www.c-sharpcorner.com/article/C-Sharp-heaping-vs-stacking-in-net-part-i/.

Upvotes: 1

Related Questions