neo2862
neo2862

Reputation: 1526

How are variables on the stack accessed?

Suppose we have these local variables:

int a = 0;
int b = 1;
int c = 2;
int d = 3;

As far as I know, these will be allocated on the system stack, like this:

|   |
| 3 | d
| 2 | c
| 1 | b
|_0_| a

Does this mean that in order to get the value of a, the values of d, c and b must first be popped out of the stack? If so, where do these values go? Does this mean that accessing more recently declared variables will be faster? Or am I missing something (which I suspect is the case), and the whole thing works in some other way?

EDIT: thanks, guys!

Upvotes: 11

Views: 2001

Answers (3)

Chris de Vries
Chris de Vries

Reputation: 57605

Does this mean that in order to get the value of a, the values of d, c and b must first be popped out of the stack?

The code emitted simply moves the stack pointer the correct number of bytes when entering the function. It moves it back the same distance when leaving the function. Thus, it does not pop off the variables individually. Assuming an int is 4 bytes, the example you gave would move the stack pointer 16 bytes. It actually moves it further than this because of other information in the stack frame such as the return address.

Upvotes: 2

Christoph
Christoph

Reputation: 169553

Or am I missing something

You're missing that the stack resides in regular memory, which allows random access - just add the appropriate offset to the frame pointer (the bottom of the 'local' stack) and you get a pointer to the memory cell holding the value.

Upvotes: 8

starblue
starblue

Reputation: 56762

The local variables on the stack are usually accessed relative to the so-called frame pointer, which points at the start of your stack frame. It would also be possible to do this relative to the stack pointer, but since this moves around during evaluation of expressions it is more difficult to keep track of.

In practice such variables may also be kept in processor registers.

Upvotes: 19

Related Questions