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.
In Python, on the other hand, variables declared in if-statements, for-loop blocks, and while-loop blocks are not local variables, and stay in scope outside of the block.
For the most part, loops do not have their own scope, so the variable's scope will be the scope of wherever the for loop lives. With that in mind, if the for loop is within a function, it will have local scope. One exception would be using let x = something in Javascript.
Local Variable: A local variable is a type of variable that we declare inside a block or a function, unlike the global variable. Thus, we also have to declare a local variable in c at the beginning of a given block. A user also has to initialize this local variable in a code before we use it in the program.
Yes you are returning an array, which is actually a pointer behind the scenes, to the address of the memory location where the contents of the variable you've initialised is stored.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With