I was trying out the following C code:
void main()
{
int i;
for(i = 0; i< 10; i++)
{
int num;
printf("\nthe variable address is: %p", &num);
}
getch();
}
I had expected it to either throw an error or declare num multiple times but instead, the output shows the same value for &num, for all the iterations of the for loop.
What is the reason behind this behavior? It seems that irrespective of having the declaration in the for loop, the actual declaration/definition happens just once.
Can someone help me understand this behavior?
To help illustrate this, compare this:
This again shows that
numalways has the same address, but also is initialised with a distinct value each iteration.The idea with the stack is that its layout is defined at compile time; each stack variable maps to an address on the stack with the stack frame.
Another thing to hlep you get this is to consider that if each iteration “allocated” a new variable, how would a small machine handle a large loop?
See: Call Stack