CBFalconer said:
It has nothing to do with 'using the same memory'. The point is
that you are initializing the variable on entry to the while loop.
You want that initialization code to be executed on every pass
through the loop, not on the entry to the loop. So I recommend
saying what you mean.
In addition using that construct requires a C99 compiler. My
method only requires a C90 compiler.
Huh??
Here's the code in question:
| while( current != NULL )
| {
| name* temp = current;
| current = current->next;
| free( temp );
| }
temp is initialized on each execution of the compound statement, i.e.,
on each iteration of the loop, which is exactly what you want.
Declarations at the beginning of a compound statement have always been
supported; they are not a C99-specific feature.
Here's a complete (but non-functional) program that incorporates the
above fragment. Compile it with whatever strict C90 options you like
to convince yourself that it doesn't depend on C99. And consult the
standard to convince yourself that temp is initialized on each
iteration of the loop, exactly as it needs to be, and there's no
benefit to moving its declaration outside the loop.
#include <stdlib.h>
int main(void)
{
typedef struct name {
struct name *next;
} name;
struct name *current = NULL;
while( current != NULL )
{
name* temp = current;
current = current->next;
free( temp );
}
return 0;
}