I'm not sure why this is cross-posted to comp.sources.d (I'm reading
it in comp.lang.c), but I'll leave the newsgroups header alone for
now.
ma**********@ly cos.com writes:
My simplistic mind tells me that having local variables within looping
constructs is a bad idea. The reason is that these variables are
created during the beginning of an iteration and deleted at the end of
the iteration. Kindly note that I am not talking about dynamically
allocating memory within a loop, which is a perfectly valid operation
(albeit with a chance of resulting in a memory leak, unless we are
careful).
I wouldn't worry about it. An implementation could easily allocate
all local variables, including those in inner scopes, on entry to a
function; variables in disjoint scopes could overlap. I suspect (but
I've never checked) that most compilers actually do this.
For example (assuminging 4-byte ints, offsets measured from
something-or-other) a sensible implementation might do something like
this:
void func(void)
{
/* Allocate 12 bytes of stack space on entry */
int a; /* offset 0 */
for (blah;blah;blah ) {
int b; /* offset 4;
}
while (blah) {
int c; /* offset 4 */
int d; /* offset 8 */
}
/* Deallocate 12 bytes of stack space on exit */
}
Chances are that allocating 12 bytes of stack space takes no more time
than allocating 4 bytes of stack space.
The alternative of allocating locals on entry to their scope, and
deallocating them on exit, could be expensive; it would save some
space temporarily, but the maximum usage within the function would be
the same. The only case where it might make sense is something like
this:
void strange(void)
{
int x;
do_some_stuff() ;
if (rare_condition ) {
int huge_array[MANY];
do_some_more_st uff();
}
}
but even then the benefit is questionable.
Note that this is all about possible implementation strategies (which
I suppose makes it marginally off-topic). As far as the language is
concerned, variables are created when their scope is entered and cease
to exist when their scope is exited. But since the standard doesn't
say how the creation or destruction of a variable is to be performed,
an implementation is free to optimize it by creating it early and/or
destroying it late.
If you're really worried about it, get your compiler to generate an
assembly listing and take a look at the generated code.
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.