Re: declaration of variable in for loop



On Wed, 30 Jan 2008 22:47:11 -0800, DDD wrote:

On Jan 31, 2:25 pm, poornimampra...@xxxxxxxxx wrote:
Hi there,

suppose i have piece of code like
main()
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}

}

When i see the address of K its same in all iterations.That means K is
only defined once at a time.
Is it because each for loop execution is considered as separte
block,its allocating in the same address? or is it allocated memory
only once?

because each for loop execution is considered as separte block. And the
memory address of K should be random.

Why? There's no reason - as far as I can tell from the standard - to
expect that it _will_ have a random address, just that it _can_.

The optimizer may have found that each iteration does the equivalent of
"jump over N bytes, leaving that space to hold k", which is a waste of
time in this code - move it out of the loop and the loop will run faster,
the code can't tell the difference and the address won't change.

.



Relevant Pages

  • Re: declaration of variable in for loop
    ... int i,j; ... or is it allocated memory only once? ... because each for loop execution is considered as separte block. ...
    (comp.lang.c)
  • declaration of variable in for loop
    ... int i,j; ... Is it because each for loop execution is considered as separte ... or is it allocated memory only once? ...
    (comp.lang.c)
  • Re: declaration of variable in for loop
    ... Is it because each for loop execution is considered as separte ... or is it allocated memory only once? ... because you asked for it with the & operator, and the existence of ...
    (comp.lang.c)