473,591 Members | 2,899 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Declaration of variables

I have always felt that you should only declared variables as needed,
and implicitily it seems many authors to encourage it, but the other
day a friend told me that declaring variables inside a loop wasn't good
practice, something like:

for(int i=0; i<size-1; ++i){
int aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

should be written like:

int aux;
for(int i=0; i<size-1; ++i){
aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

What do you think? Thaks!

Mar 6 '06 #1
39 2392
Gaijinco wrote:
I have always felt that you should only declared variables as needed,
and implicitily it seems many authors to encourage it, but the other
day a friend told me that declaring variables inside a loop wasn't good
practice, something like:

for(int i=0; i<size-1; ++i){
int aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

should be written like:

int aux;
for(int i=0; i<size-1; ++i){
aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

What do you think? Thaks!


I think it's your friend who should _prove_ it to you that there is some
advantage to his method.

V
--
Please remove capital As from my address when replying by mail
Mar 6 '06 #2
Gaijinco wrote:
I have always felt that you should only declared variables as needed,
and implicitily it seems many authors to encourage it, but the other
day a friend told me that declaring variables inside a loop wasn't good
practice, something like:

for(int i=0; i<size-1; ++i){
int aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

should be written like:

int aux;
for(int i=0; i<size-1; ++i){
aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

What do you think? Thaks!

Since `aux' is only meaningful inside the loop why not limit its scope
to the block inside the loop?

On the other hand, there are situations where you wouldn't want to do
this, when, for example, the variable in question is of a type that
requires significant construction overhead. This, however, seems not to
be one of those situations. ;-)

HTH,
--ag

--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com
"You can't KISS* unless you MISS**"
[*-Keep it simple, stupid. **-Make it simple, stupid.]
Mar 6 '06 #3
Gaijinco wrote:
I have always felt that you should only declared variables as needed,
and implicitily it seems many authors to encourage it, but the other
day a friend told me that declaring variables inside a loop wasn't good
practice, something like:

for(int i=0; i<size-1; ++i){
int aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

should be written like:

int aux;
for(int i=0; i<size-1; ++i){
aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

What do you think? Thaks!


Your friend might think that the first code is slower. In some few similar
cases it might indeed be slower. You shouldn't worry about that.

Tell your friend that premature optimization is the root of all evil. The
most important resource to optimize is programmer time. Programmers must
write clean code first, because it's easy to make beautiful code fast than
fast code beautiful.

After your for loop ends, aux's only meaning is "the last variable in the
array". Subsequent statements should not rely on the for loop "leaking" its
last aux value out. If they want the last value in the array, they should
get it themselves. They should decouple as much as possible from the rest
of your program, including the statements just before them.

Always give any identifier the narrowest scope and access possible. Don't
use global variables or public data members. Never create a variable
without giving it an initial value. Put all these rules together, and you
have many reasons to put int aux inside the loop.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 6 '06 #4
Gaijinco posted:
I have always felt that you should only declared variables as needed,
and implicitily it seems many authors to encourage it, but the other
day a friend told me that declaring variables inside a loop wasn't good
practice, something like:

for(int i=0; i<size-1; ++i){
int aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

should be written like:

int aux;
for(int i=0; i<size-1; ++i){
aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

What do you think? Thaks!

Here's how I'd to do it:

for (int aux, i = 0; i < size -1; ++i)
{
...
}
If I had to pick one of the two ways you posted, then I'd put the
variable declaration outside the for loop. Does it make a difference?
Probably not... but at least your safe in the thought that memory isn't
being continuously allocated and deallocated for each iteration of the
loop.

Also as another Artie said, if you dealing with something like an
std::string, then definitely put it *outside* the loop.

The final reason is that I like consistency; if I'm going to put
std::string outside the loop, then I'll put an "int" outside the loop
too.

-Tomás

Mar 6 '06 #5
On 6 Mar 2006 12:13:48 -0800, "Gaijinco" <ga******@gmail .com> wrote:
I have always felt that you should only declared variables as needed,
and implicitily it seems many authors to encourage it, but the other
day a friend told me that declaring variables inside a loop wasn't good
practice, something like:

for(int i=0; i<size-1; ++i){
int aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

should be written like:

int aux;
for(int i=0; i<size-1; ++i){
aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}
Why? Both versions are essentially the same. The performance is the
same. The second version is bad style because it doesn't obey to the
'minimal scoping rule'.
What do you think? Thaks!


Your friend has gone astray. Lead him back to the right path.
Roland Pibinger
Mar 6 '06 #6
Tomás posted:
Gaijinco posted:
I have always felt that you should only declared variables as needed,
and implicitily it seems many authors to encourage it, but the other
day a friend told me that declaring variables inside a loop wasn't good practice, something like:

for(int i=0; i<size-1; ++i){
int aux = array[i]; array[i]=array[i+1]; array[i+1]=aux; }

should be written like:

int aux;
for(int i=0; i<size-1; ++i){
aux = array[i]; array[i]=array[i+1]; array[i+1]=aux; }

What do you think? Thaks!

Here's how I'd to do it:

for (int aux, i = 0; i < size -1; ++i)
{
...
}
If I had to pick one of the two ways you posted, then I'd put the
variable declaration outside the for loop. Does it make a difference?
Probably not... but at least your safe in the thought that memory isn't
being continuously allocated and deallocated for each iteration of the
loop.

Also as another Artie said, if you dealing with something like an
std::string, then definitely put it *outside* the loop.

The final reason is that I like consistency; if I'm going to put
std::string outside the loop, then I'll put an "int" outside the loop
too.

-Tomás

Furthermore, if your worried about scope, God gave us curly braces for a
reason:

int main()
{
//Some code

{
int aux;
for (int i; i < size -1; ++i)
{
//Some Code
}
}

//Some more code
}
-Tomás
Mar 6 '06 #7
Tomas wrote:
Here's how I'd to do it:

for (int aux, i = 0; i < size -1; ++i)
{
...
}
Why?

The scope is not as narrow as possible. It's one tick wider, into a scope
where it's not needed.
If I had to pick one of the two ways you posted, then I'd put the
variable declaration outside the for loop. Does it make a difference?
Probably not... but at least your safe in the thought that memory isn't
being continuously allocated and deallocated for each iteration of the
loop.
That's premature optimization.

Further, the earliest definitions of C state that storage for all local
variables in a function allocate when the function enters, regardless of
their scope. I'm sure The Standard has since mutilated that requirement,
but I can't imagine a compiler doing it any other way.
Also as another Artie said, if you dealing with something like an
std::string, then definitely put it *outside* the loop.
Why? Have you time tested it?

What if std::string inside a loop fit in your CPU cache, but outside the
loop it overflowed your cache and caused memory thrashing?
The final reason is that I like consistency; if I'm going to put
std::string outside the loop, then I'll put an "int" outside the loop
too.


Then put it consistently inside the loop. This improves the odds it will go
away!

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 6 '06 #8
"Tom?s" <NU**@null.null > wrote:
The final reason is that I like consistency; if I'm going to put
std::string outside the loop, then I'll put an "int" outside the loop
too.


Found these quotes in the FAQ:

"Consistenc y is good, but it is not the greatest good" [29.5]

"The real problem is that people tend to worship consistency, and they
tend to extrapolate from the obscure to the common. That's not wise."
[10.19]

(Granted, they are talking about different situations, but nonetheless
they are good pieces of advice to keep in mind in general.)

--
Marcus Kwok
Mar 6 '06 #9
Tomás wrote:
Gaijinco posted:

I have always felt that you should only declared variables as needed,
and implicitily it seems many authors to encourage it, but the other
day a friend told me that declaring variables inside a loop wasn't good
practice, something like:

for(int i=0; i<size-1; ++i){
int aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

should be written like:

int aux;
for(int i=0; i<size-1; ++i){
aux = array[i];
array[i]=array[i+1];
array[i+1]=aux;
}

What do you think? Thaks!
Here's how I'd to do it:

for (int aux, i = 0; i < size -1; ++i)
{
...
}
If I had to pick one of the two ways you posted, then I'd put the
variable declaration outside the for loop. Does it make a difference?
Probably not... but at least your safe in the thought that memory isn't
being continuously allocated and deallocated for each iteration of the
loop.

Also as another Artie said, if you dealing with something like an
std::string, then definitely put it *outside* the loop.


I think you've overstated my comments to an extent; I'm not sure I would
call a std::string something that involves `significant construction
overhead'. In any event, as noted elsethread, it's an optimization in
any case and not to be undertaken lightly.
The final reason is that I like consistency; if I'm going to put
std::string outside the loop, then I'll put an "int" outside the loop
too.


It's only worth the ugliness of doing that if it's demonstrably worth
that ugliness in terms of *needed* performance.

Whenever possible localilty is *good*!

Cheers,
--ag

--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com
"You can't KISS* unless you MISS**"
[*-Keep it simple, stupid. **-Make it simple, stupid.]
Mar 6 '06 #10

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

Similar topics

83
6459
by: Alexander Zatvornitskiy | last post by:
Hello All! I'am novice in python, and I find one very bad thing (from my point of view) in language. There is no keyword or syntax to declare variable, like 'var' in Pascal, or special syntax in C. It can cause very ugly errors,like this: epsilon=0 S=0 while epsilon<10: S=S+epsilon
2
8814
by: Thomas Matthews | last post by:
Hi, I'm getting linking errors when I declare a variable in the global scope, but not inside a function. The declarations are the same (only the names have been changed...). class Book { public: Book()
5
562
by: Daniel Nichols | last post by:
I've noticed that in a C module (.c, .h file combination) that if you create a function's definition before it is used in other functions than a declaration is not necessary. I believe if the compiler can find the definition of the function prior to encountering the use of the function it will generate the prototype itself. I don't currently use this feature, I explicitly create declarations for all functions in a header file. However, I...
2
2312
by: Nils Emil P. Larsen | last post by:
Hello I have read about a C shared library which I want to use in my C program. (It's a library to encode/decode packets from/to a serial bus running with the SNAP-protocol). Unfortunatly there is no source code available, just a C file with function declarations like: long SendData(TXData)Type_TXData *TXData;
7
2048
by: Peter Merwood | last post by:
Hi I've been coding in VB for a good number of years and have recently made the switch to VB.NET. When coding I put all my declaration/Dim statements at the beginning of the Sub or Function before any "real" code. VB.NET lets you scatter declaration statements throughout a Sub or Function and it seems even have conditional declaration statements, ie; If x = "something" then dim y as Integer
18
3216
by: noridotjabi | last post by:
Whilest I was browesing a tutorial today I came across the infromation that in standard C variables must be decalred at the beginning of a block. Meaning: /****************************************************/ /* ... usual includes and such */ int var = 1; if(var = 1){ printf("hello world\n");
25
2785
by: venky | last post by:
Hi main() { int x; /* it declaration or defination??*/ }
18
2109
by: sunny | last post by:
Hi Why does C allows declaration of variable inside switch block. ex: foll prg does not gives "undeclared "b" error msg. but also does not initialize b to 20 int a=1; switch(a) { int b=20; case 1: printf("b is %d\n",b);
9
8870
by: Jess | last post by:
Hello, I was told that if I declare a static class constant like this: class A{ static const int x = 10; }; then the above statement is a declaration rather than a definition. As I've *defined* "x"'s value to be 10, isn't above statement a
14
13041
by: subramanian100in | last post by:
Consider the following program: #include <iostream> using namespace std; int main() { int i;
0
7935
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
8366
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
7995
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
6642
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
5735
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
5400
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
3851
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
3893
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1467
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.