开发者

Declaring variablle within a for loop

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 d开发者_Python百科eclare 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?


You're printing the address of a stack-allocated variable. The variable's scope is the for loop. Theoretically, the variable is created at the line int num; and its memory released at the closing for bracket. The memory layout is strictly compiler-dependent.

It might be that your compiler is smart enough to know it can reuse that memory, or it may be that memory is free and is chosen by the compiler for your variable storage.

It can also be that the optimizer is telling the compiler its okay to reuse num.

It's all down to the compiler, however, just because it has the same address doesn't mean it is only declared/defined once.


To help illustrate this, compare this:

   int i;
   int val = 0;
   for(i = 0; i< 5; i++)
   { 
      int num = val++;
      printf("\nthe variable address is: %p", &num);
      printf("\nthe value is: %d", num);
   }

This again shows that num always 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜