473,836 Members | 1,501 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Local variables within looping constructs

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

Nov 14 '05 #1
5 2422
ma**********@ly cos.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. [...]


My simplistic mind tells me that I have no idea what the
cost of creating and deleting a local variable might be. It
might be huge, in which case your aversion would make sense.
Or it might be zero, in which case you're just being silly.
It might even be negative (yes!), in which case you're
completely in the wrong camp.

It is temptingly -- too temptingly -- easy to outguess a
compiler. It is impossible to outguess all compilers. And,
of course, "It is a capital offense to theorize before one
has data." What data have you measured?

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 14 '05 #2
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.
Nov 14 '05 #3
> Chances are that allocating 12 bytes of stack space takes no more
time
than allocating 4 bytes of stack space.


That would be my guess. So far as I am aware all memory that you use
will either be:

Coming off the stack
Coming off the heap
Preinitialized memory (like constants or strings embedded in the
source)

If it is coming off the stack then you just add "12" to the pointer to
the top of your stack. True, it might be spending time making sure to
zero that memory.

If it is coming off the heap then there might be a speed hit. And I
suppose it is up to the compiler to determine how it wants to allocate
memory for your local variables...but I would very much guess it's not
allocating from the heap.

If it is preinitialized then the value is just sitting there in memory
and there isn't any allocation during runtime (but rather when the
application was loaded.)

But as was stated before, I would recommend trying both ways and timing
them to see what the difference is. But even if it is faster, I would
note that the first rule of optimization is to not pre-optimize! In the
end 90 of what makes your code go slow will be a bad algorithm that
needs to be cleaned up. Getting an extra 0.1% off the rest of your code
will not only be worth it, but can make the chances for bugs to happen
increase since optimized code will generally not be the most
programming-safe-type code. Best to keep the scope of all variables as
small as you can get it.

Nov 14 '05 #4
On 28 Jan 2005 17:17:09 -0800, ma**********@ly cos.com
<ma**********@l ycos.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)
Nov 14 '05 #5
"Chris Williams" <th********@yah oo.co.jp> wrote:
Chances are that allocating 12 bytes of stack space takes no more time
than allocating 4 bytes of stack space.


That would be my guess. So far as I am aware all memory that you use
will either be:

Coming off the stack
Coming off the heap
Preinitialized memory (like constants or strings embedded in the
source)


Well, yes and no. _Most_ memory you use in _most_ current desktop
environments will do so. But the Standard does not require any memory to
come from any kind of structure - all it requires is that memory you get
from malloc() behaves a certain way, and memory assigned to int a[14]
behaves another way, and so forth.

Of course, this makes your final point - that there's no way to know
which is faster - only more true.

Richard
Nov 14 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2254
by: TinTin | last post by:
Hello, How do I concatinate a variable. Here's the scenarios: declare @var1 varchar(20) declare @var2 varchar(20) declare @var3 varchar(20) declare @var4 varchar(20) .. ..
2
2143
by: Oliver Corona | last post by:
I am wondering if anyone has any insights on the performance benefit (or detriment) of declaring local variables instead of referencing members. Is allocating memory for a new variable more efficient than repeatedly referencing the member in a loop? Maybe using a string isn't the best example, but hopefully you get the idea! * example (referencing member):
12
3299
by: Olumide | last post by:
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is an absolutely fantastic book; however on page 175 (topic: operator overlaoding), there the following code snippet: inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global function { MFVec res = z1; res += z2 return res; // WHY???
12
3114
by: Michael B Allen | last post by:
Which style of local variable declaration do you prefer; put everything at the top of a function or only within the block in which it is used? For example; void fn(struct foo *f, int bar) { struct abc d; int i;
9
2213
by: Stefan Turalski \(stic\) | last post by:
Hi, I done sth like this: for(int i=0; i<10; i++) {...} and after this local declaration of i variable I try to inicialize int i=0;
7
3160
by: Edward Yang | last post by:
A few days ago I started a thread "I think C# is forcing us to write more (redundant) code" and got many replies (more than what I had expected). But after reading all the replies I think my question about local variable initialization is still not solved. And some of the replies forked into talking about out parameters. And the thread is becoming way too deep. So I open a new thread here. My question in the previous thead has turned...
5
2443
by: Michal Kwiatkowski | last post by:
Hi! I'm building a class that most of methods have similar intro, something like this: def method(self): var_one = self.attr_one var_two = self.attr_two.another_attr empty_list =
114
7893
by: Jonathan Wood | last post by:
I was just wondering what naming convention most of you use for class variables. Underscore, "m_" prefix, camel case, capitalized, etc? Has one style emerged as the most popular? Thanks for any comments. --
55
6276
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in C# in some way? Or maybe no, because it is similar to a global variable (with its scope restricted) which C# is dead against? Zytan
0
10860
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10560
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6984
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5659
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5831
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4466
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4026
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3116
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.