Reputation: 25
I can't get one thing: when I declare variables (local) inside of a function, they are allocated on a stack. How does referencing happen? If I want to assign another value to a local variable, do I need to know where exactly on a stack a variable is located? Is this piece of information stored anywhere?
Upvotes: 0
Views: 63
Reputation: 320
You don't have to care about the location of the variable on stack. While compiling the code, compiler will take care of these things about where the variable will be stored and how it will be referenced.
Upvotes: 3
Reputation: 362
Suppose your code looks like this:
void main() {
int a,b;
a = 5;
b = 7;
printf("%p\n", &a);
}
This code should allocate two ints, 'a' and 'b', on the stack. It will then print out the address of 'a' and exit. When main is called, the stack is going to be pretty empty. A bit of compiler-generated code will allocate a bit of space on the stack, so that it looks like this:
- 'a': Random data
- 'b': Random data
When you say 'a = 5;', you're just telling the compiler to generate some code that will "put the number 5 in the memory location that we call 'a'". This memory location 'a' just happens to be on the stack, so the compiler puts 5 into that spot on the stack.
It's pretty much the same for 'b':
When we get a reference to 'a', we get an address that's on the stack because that's where the compiler decided to store 'a'. If 'a' was a global variable, the address wouldn't be on the stack.
Not that you need to care, however. The compiler should take care of all this stuff for you. That's the great thing about C compilers, and it's why we use them. The C compiler can put any of your variables wherever it wants and you don't need to care. You can just say "Put 5 in the spot that we call 'a'" (a = 5;) or "Print out the address of wherever you put 'a'" (printf("%p\n", &a);).
In short, function variables are allocated on the stack. You don't need to know where on the stack to be able to set them, and you don't need to care where they are because that's what compilers are for.
Upvotes: 2