memory allocation for auto variables in a loop

Hi,

I have the following simple program which prints out the address of a local variable inside loop. I assume the address of that variable changes by iteration, but it was not. Could someone explain me why?

#include <iostream>

int main() {

for(int i=0; i<5; i++) {
float p = 3.14;
std::cout << "addr of p : " << &p << std::endl;
}

return 0;
}

result:
addr of p : 0x7fffda254c88
addr of p : 0x7fffda254c88
addr of p : 0x7fffda254c88
addr of p : 0x7fffda254c88
addr of p : 0x7fffda254c88

Thanks,
DW
The local variable is destroyed after each iteration, so it suggests itself to reuse the same address for the next one.

Why do you think it should change?
Hi,

I thought it is not necessarilly be same all the time. So for example, if I run this on thread, it should be different, shouldn't it?

Thanks,
I thought it is not necessarilly be same all the time.

No one says it has to be, that's up to the compiler.

So for example, if I run this on thread, it should be different, shouldn't it?

But you're running this in only one thread.
Topic archived. No new replies allowed.