views:

198

answers:

3

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!

+5  A: 

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.

Christoph
+15  A: 

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.

starblue
+1 for the explanation of stack pointer vs. frame pointer
Christoph
+1 again for explanation
cbrulak
+1  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?

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.

cdv
thanks! (and the link was really useful too)
Botond Balázs