Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 768
neo2862 Avatar asked Feb 08 '09 12:02

neo2862


1 Answers

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.

like image 200
starblue Avatar answered Oct 14 '22 13:10

starblue