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.
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
.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
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.
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: