473,587 Members | 2,494 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 2409
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
2239
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
2131
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
3271
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
3080
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
2193
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
3136
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
2429
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
7810
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
6185
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
7924
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8219
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...
1
7978
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8221
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6629
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5722
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...
1
2364
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
1
1455
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1192
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.