Here is the C code snippet.
#include<stdio.h>
int N = 10;
while (N--) {
int *a;
printf("%p\n", &a);
}
The running results(Compiler: tdm-gcc 4.9.2 64-bit release, os: win11 ) show that the program prints the same value in N loops. Is this a random event, or is it caused by some mechanism in the C language?
ais a local variable inside of the loop body. You are printing the address of the variable itself, not the address it is pointing at. The variable enters and leaves scope on each loop iteration, and when it goes out of scope its memory becomes available for reuse. So, when one iteration is finished, the compiler is allowed to reuse that same memory on the next iteration for the same variable, if it wants to. But this is not a guarantee, so don't rely on it.