Re: Local variables within looping constructs
From: Chris Croughton (chris_at_keristor.net)
Date: 01/29/05
- Next message: Joe Wright: "Re: Why the Range of Int is less by one at positive side?........."
- Previous message: Chris Croughton: "Re: using system("xxxxx")"
- In reply to: masood.iqbal_at_lycos.com: "Local variables within looping constructs"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 29 Jan 2005 12:28:42 +0000
On 28 Jan 2005 17:17:09 -0800, masood.iqbal@lycos.com
<masood.iqbal@lycos.com> wrote:
> 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).
It depends on the cost of 'creating' such a variable. For a simple
variable like an int there may well be no cost at all. For instance, on
one compiler I know the constructs:
void func(void)
{
int i;
for (i = 0; i < 10; ++i)
{
int j;
...
}
...
for (i = 0; i < 10; ++i)
{
int k;
...
}
}
will result in a stack structure
space for i
space for j and k (shared)
allocated when the function is entered.
> 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 = ...;...;)
That isn't within the loop, though, that is exactly equivalent to
{
int i;
for (i = initial; condition; stuff)
...
}
This is true in both C (C99 standard) and C++, they are defined to be
identical.
It is also identical to
{
int i;
i = initial;
while (condition)
{
...
stuff;
}
}
> I have never seen anyone propose this approach. Are there any
> drawbacks that I am not seeing?
Clarity. Reducing the abount of nesting of braces and keeping
variables local to where they are used inproves clarity and reduces the
possibilities of mistakes when the code is edited (inadvertently using a
variable used in an outer loop for example, if you always declare your
loop variable when it is wanted and it is always removed after that then
it minimises the risk).
Chris C (note followups to c.l.c only)
- Next message: Joe Wright: "Re: Why the Range of Int is less by one at positive side?........."
- Previous message: Chris Croughton: "Re: using system("xxxxx")"
- In reply to: masood.iqbal_at_lycos.com: "Local variables within looping constructs"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|