poornimamprabhu@gmail.com 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.
For some compilers like lcc-win this is the case.
lcc-win allocates all local variables of the function, no
matter what scope, at the start of the function. The stack is not
modified within the function. This is done for obvious
performance reasons. Imagine that at the end of the
block the stack was adjusted, and at the start space
for the variable would be created. This would make for
at least 2 instructions per block iteration... not a good
idea.
Of course, the *scope* of the variable is ONLY within the
enclosing block. After the block is left, there is no way to access
that stack position within C, unless you take
the address of the local variable.
main()
{
int i,j, *pint;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
pint=&i;
}
*pint = 789; // Accessing illegal storage
}
This would work on lcc-win since the storage is still valid.
I would not do this since it is absolutely non portable.
Other compilers could implement other strategies.
For instance
main()
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}
}
The second "k" could be aliased by the compiler to the first one
and stored at the same memory location.
> 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?
For lcc-win it is the second.
--
jacob navia
jacob at jacob point remcomp point fr
logiciels/informatique
http://www.cs.virginia.edu/~lcc-win32