473,320 Members | 1,910 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

variable declaration style

Let's say I had code like these, what is better?

for(;;)
{
bool finished;

do
{
}
while (!finished);
}

or

bool finished;

for(;;)
{

do
{
}
while (!finished);
}

Whenever declaring variables I tend to think like what a compiler does.
What if a compiler allocates from the stack whenever it finds a variable
definition?
Mar 8 '07 #1
12 1902
John Doe wrote:
Let's say I had code like these, what is better?
The former. The simple rule is: unless some other requirement prevents
it, keep the tightest scope for any variable you declare.
>
for(;;)
{
bool finished;

do
{
}
while (!finished);
}

or

bool finished;

for(;;)
{

do
{
}
while (!finished);
}

Whenever declaring variables I tend to think like what a compiler
does. What if a compiler allocates from the stack whenever it finds a
variable definition?
So? It's not specified, the compiler is free to do whatever it sees
fit. Why do you care, anyway?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 8 '07 #2
The former. The simple rule is: unless some other requirement prevents
it, keep the tightest scope for any variable you declare.
thanks
So? It's not specified, the compiler is free to do whatever it sees
fit. Why do you care, anyway?

V
because all kinds of allocation take time and, say 10000s of stack
allocations could make an impact on execution time. It figures that it's
unspecified, but what is the rule-of-thumb? What do modern C++ compilers
usually do?
Mar 8 '07 #3
John Doe wrote:
[snip]
because all kinds of allocation take time and, say 10000s of stack
allocations could make an impact on execution time. It figures that it's
unspecified, but what is the rule-of-thumb? What do modern C++ compilers
usually do?
They optimize that away.

- J.
Mar 8 '07 #4
"John Doe" <NO******************@yahoo.comwrote in message
news:es**********@registered.motzarella.org...
because all kinds of allocation take time and, say 10000s of stack
allocations could make an impact on execution time. It figures that it's
unspecified, but what is the rule-of-thumb? What do modern C++ compilers
usually do?
Rule of thumb: People are more important than computers. Therefore, you
should strive to make your programs as easy as possible to understand.

If you are concerned about performance, measure the program once it's
complete and working.
Mar 8 '07 #5
John Doe wrote:
>The former. The simple rule is: unless some other requirement prevents
it, keep the tightest scope for any variable you declare.

thanks
>So? It's not specified, the compiler is free to do whatever it sees
fit. Why do you care, anyway?

V

because all kinds of allocation take time and, say 10000s of stack
allocations could make an impact on execution time.
What exactly would you expect a "stack alocation" to look like?
It figures that it's unspecified, but what is the rule-of-thumb? What do
modern C++ compilers usually do?
Probably nothing.

Mar 8 '07 #6
* John Doe:
* Victor Bazarov:
>Why do you care, anyway?

because all kinds of allocation take time and, say 10000s of stack
allocations could make an impact on execution time. It figures that it's
unspecified, but what is the rule-of-thumb? What do modern C++ compilers
usually do?
Stack allocation is mostly a conceptual device, and conceptual
operations do not necessarily take time.

A modern compiler implements the C++ automatic storage stack (LIFO
automatic allocation) by reserving a suitably large chunk of (machine)
stack space on function entry, using one or at most three instructions.

Disregarding function calls, further (machine) stack allocations do not
(typically) take place during execution of the function's code, except
if it uses extensions such as _alloca() or C99 dynamic arrays.
Initializations of local objects can still take time. However, local
variables of built-in types are by default not initialized, and anyway,
modern compilers also do such things as moving invariant code out of
loops, so as others have remarked, /measure/ before trying to optimize.

Btw., please include some mention of whom you're quoting.

I've added back the missing information above.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Mar 8 '07 #7
"John Doe" <NO******************@yahoo.comwrote in message
news:es**********@registered.motzarella.org...
>The former. The simple rule is: unless some other requirement prevents
it, keep the tightest scope for any variable you declare.

thanks
>So? It's not specified, the compiler is free to do whatever it sees
fit. Why do you care, anyway?

V

because all kinds of allocation take time
Some kinds take longer than others.
and, say 10000s of stack allocations could make an impact on execution
time.
First, note that there's no requirement by the language that a stack
be used for anything at all. However, many implementations do indeed
implement local objects and function parameters with a stack. But
on every machine I've worked with, 'allocation' of stack data involves
nothing more than assigning a value to a single register. IMO pretty
darn quick operation.
It figures that it's unspecified, but what is the rule-of-thumb?
Write clear, understandable, maintainable code. Measure performance.
Only consider optimizing at source code level if performance does not meet
specifications. And when doing this, the usual best thing to optimize is
the algorithms, not 'low level' code structure.
>What do modern C++ compilers usually do?
They optimize, almost always better than a coder could.

-Mike
Mar 8 '07 #8
John Doe wrote:
Let's say I had code like these, what is better?

for(;;)
{
bool finished;

do
{
}
while (!finished);
}

or

bool finished;

for(;;)
{

do
{
}
while (!finished);
}
Neither, finished is not initialised, so what finished will result in
causing the loop to terminate is going to be random. However, if you
initialise the finished variable, you will want to do the former for the
same reasons that were already stated in the rest of the thread.
Adrian
Whenever declaring variables I tend to think like what a compiler does.
What if a compiler allocates from the stack whenever it finds a variable
definition?
Yeah, that is sometimes good in low level hardware apps using old
compilers when every clock cycle counts, but the allocation of memory on
the stack is not as big a deal as the initialisation, and you will have
to initialise it some where anyway, so you might as well do it at
initialisation. The optimiser will take care of a whole whack of
things, but mistake proofing is not one of them. Write your code to
keep mistakes from happening and let the optimiser do its job.
Adrian
Mar 9 '07 #9
Dnia Thu, 08 Mar 2007 17:17:23 +0100, John Doe napisa³(a):
>because all kinds of allocation take time
Not all kinds :) Only the dynamic ones ;) [new/delete].
Local objects are being allocated on the stack by
decreasing stack pointer to make it point "above"
the allocated local objects' total size.
and, say 10000s of stack allocations could make
an impact on execution time.
Instructions also have impact on execution time ;)
It figures that it's unspecified, but what is the
rule-of-thumb? What do modern C++ compilers usually do?
Modern compilers I know makes allocation of all local
objects of a particular block once a time [on the block
entry] by establishing a stack frame [remembering the
stack pointer in the base register, and decreasing the
stact pointer by the total size of all local objects],
and "deallocate" it upon exit from that block [by
restoring the old value of stack pointer].

--
SasQ
Mar 10 '07 #10
Hi,

I am an amateur programmer who keeps on lurking on this forum to pick
up a few tit-bits of tips here and there.

I haven't understood complexity of the solutions provided. This is how
I see the problem:

The thing wrong with the code

for(;;)
{
bool finished;

do
{

} while (!finished);
}

in my opinion is the variable 'finished' is declared - unnecessarily -
repeatedly. A thumb of rule I learnt is that such a thing is an
unefficient programming practice.

Another rule of thumb that was posted earlier is that the scope of the
variable should be as tight as possible.

What is wrong with following two solutions which satisfy both of the
above rules?

{
bool finished;
for(;;)
{
do
{

} while (!finished);
}
}

OR

for(;;)
{
static bool finished;
do
{

} while (!finished);
}
}

- Sanjay Kulkarni
===============

Mar 24 '07 #11
Sanjay Kulkarni wrote:
What is wrong with following two solutions which satisfy both of the
above rules?

{
bool finished;
for(;;)
{
do
{

} while (!finished);
}
}
You can use a shorter and simpler approach:

for (bool finished= false; ! finished; )
{
// Whatever
}

--
Salu2
Mar 24 '07 #12
Sanjay Kulkarni wrote:
Hi,

I am an amateur programmer who keeps on lurking on this forum to pick
up a few tit-bits of tips here and there.

I haven't understood complexity of the solutions provided. This is how
I see the problem:

The thing wrong with the code

for(;;)
{
bool finished;

do
{

} while (!finished);
}

in my opinion is the variable 'finished' is declared - unnecessarily -
repeatedly. A thumb of rule I learnt is that such a thing is an
unefficient programming practice.
That's very unlikely to be inefficient. If you have a complex object that
needs lots of initialization, then repeatedly creating it might become
inefficient, but that's not the case for bool.
Another rule of thumb that was posted earlier is that the scope of the
variable should be as tight as possible.
Yes. I'd prefer that over the other one.
What is wrong with following two solutions which satisfy both of the
above rules?

{
bool finished;
for(;;)
{
do
{

} while (!finished);
}
}

OR

for(;;)
{
static bool finished;
do
{

} while (!finished);
}
}
Which problem are you trying to solve? None of those versions should be any
faster than the one with a simple bool variable inside the for loop.

Mar 24 '07 #13

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

Similar topics

6
by: Brian Jones | last post by:
I'm sure the solution may be obvious, but this problem is driving me mad. The following is my code: class a(object): mastervar = def __init__(self): print 'called a'
83
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...
6
by: Andrew Ward | last post by:
Hi All, Could someone please tell me why this code does not compile. struct A {}; struct B { B(A &) {} }; struct C {
32
by: Wenjie | last post by:
Hello, We had a code review with the argument of whether "i" is out of scope as illustrated below: for (int i=0; i<2004; i++) { doSomething(i); }
12
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) {...
2
by: User N | last post by:
In cases where a variable can be initialized in the declaration or constructor, which approach do you take? Are there any genuine advantages to one approach over the other? Example: public...
6
by: August Karlstrom | last post by:
Hi What's the cause of the inconsistency between variable and parameter declarations in C? What's wrong with e.g. void f(int a, b; char c); August
4
by: nszabolcs | last post by:
According to http://c-faq.com/decl/decldef.html global variable declaration should have 'extern' storage class specifier, but multiple definition with at most one initialisation is a common...
6
by: gara.matt | last post by:
Hi, I was wondering, I've been reading some C++ code written by others, usually libraries and stuff, and I've come across what strikes me as a distinctive style that pervades most of the code...
112
by: istillshine | last post by:
When I control if I print messages, I usually use a global variable "int silent". When I set "-silent" flag in my command line parameters, I set silent = 1 in my main.c. I have many functions...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.