M
masood.iqbal
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).
The most common justification that I have heard for local variables
within looping constructs is that it helps localize the scope of the
variables. But isn't there another way to accomplish the same thing
----- by declaring a block outside the looping construct and declaring
local variables within that? Here's what I mean:
{
char buf1[100];
for(int i = ...;...
{
....
}
}
or
{
char buf2[100];
do
{
....
} while(...)
}
I have never seen anyone propose this approach. Are there any
drawbacks that I am not seeing?
Masood
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).
The most common justification that I have heard for local variables
within looping constructs is that it helps localize the scope of the
variables. But isn't there another way to accomplish the same thing
----- by declaring a block outside the looping construct and declaring
local variables within that? Here's what I mean:
{
char buf1[100];
for(int i = ...;...
{
....
}
}
or
{
char buf2[100];
do
{
....
} while(...)
}
I have never seen anyone propose this approach. Are there any
drawbacks that I am not seeing?
Masood