Reputation: 1821
Why does the following code output the same memory location everytime?
int x;
for (x = 0; x < 10; x++) {
int y = 10;
printf("%p\n", &y);
}
I thought that the memory location should change as each time the for-loop is run, the variable is new.
Upvotes: 19
Views: 5798
Reputation: 2487
It's a compiler optimization. Because the local variable is going out of scope and a variable of the exact same type is about to be created, it's reusing the memory address. It's important to note that this is still a "fresh" or "new" variable as far as your program is concerned.
Compare the following code snippets and output:
for (i = 0; i < 3; i++) {
int n = 0;
printf("%p %d\n", (void *)&n, n++);
}
0x7fff56108568 0 0x7fff56108568 0 0x7fff56108568 0
for (i = 0; i < 3; i++) {
static int n = 0;
printf("%p %d\n", (void *)&n, n++);
}
0x6008f8 0 0x6008f8 1 0x6008f8 2
Upvotes: 5
Reputation: 78903
The scoping rules for variables only describe the scope in which you have the right to access a local variable: from the definition to the end of its block.
This rule says nothing about the moment that space is reserved for it. A common strategy for that is to reserve space for all variables that will be needed for an invocation of a function at once, at the beginning of the function.
So when execution crosses a definition of a variable, usually nothing particularly has to be done, not a single instruction. On the other hand this leaves the value of that variable to whatever was found there previously. So the importance of initializing to a known state, as you did in your example with the = 10
.
Upvotes: 0
Reputation: 339786
Yes, the variable is new each time around, but at the end of the block any new variables on the stack are released again.
Hence next time around the stack pointer is back exactly where it was. NB: this behaviour is common, but not guaranteed by the standards.
Upvotes: 6
Reputation: 132984
Yes, you are absolutely right that the memory location could change. But it doesn't have to :). In each iteration the old variable is "destroyed" and a new one is "created" at the same place. Although any decent compiler would optimize the unnecessary "actions" away
Upvotes: 22