Variable Declaration & Initialization :: C++

Status
Not open for further replies.
Hi.

Conventionally speaking, do you declare and initialize variables at the beginning of a function or loop or right before usage.

For example:

int main()
{
char temp;

cin >> temp;
cout << "1234... & " << temp;

cin >> temp;
cout << temp;

int x;
cin >> x;
cout << temp << " & " << x;
return 0;
}

The arbitrary code above depicts declaration of variables right before usage (int x).

Which way is most convention is arguably better?

Thanks,
Kuphryn
 
I prefer to declare them as late as possible, initialize as soon as possible (ideally immediately) and give them a scope that's as short as possible.

Whilst my compiler will (in debug builds) insert code to catch most times I use uninitialized variables, I'd sooner make sure that I can't do it by not declaring a variable until I know what value to initialize it to -- so I no longer have the ability to have uninitialized variables floating about.

Declaring at the top also leads people to use hungarian bollocks -- because by the time they use the variable, they can no longer see the declaration -- and every measure should be taken to discourage its use.
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
This is one aspect of coding I'm pretty lazy with. When I'm actually thinking and/or working on "production" code, I more or less follow Peter's guideline except when it would cause a variable to be unnecessarily allocated & deleted several times. A good example would be the scope given to x in for(int x=0; x<q; ++x) - large enough that it's not created Q times, small enough that the compiler will bork if you screw up & use it where you shouldn't.

Thank God for the variable-type Tooltips in VS.NET...
 
Ooooh, no, that's one thing I'm extra careful to do, even using macro trickery to force code with variables scoped to the loop to work with MS's version 12 compiler.

The generated code doesn't reallocate it all the time (it just creates it on the stack when the function is called) -- the place at which I declare variables is purely a convenience for myself.

This is assuming primitive counters, of course, rather than anything which might get constructed multiple times if redeclared.
 
I prefer to declare my variables at the top, but that's juts a carry-over from my ANSI-C days.

One thing to watch out for is that while the variables of simple types have no initialization cost, the objects do, because for every declaration of an instance, a constructor is involved. So, if there is any chance that an object may not be used at all, it's declaration should be left until the last moment. Example
code:<HR>
Code:
void Example(int i)
{
    ...
    if( i == 0 )
    {
        MyObject Obj;
        Obj.DoStuff();
    }
    else
        cout << "i != 0\n";
}

By not declaring Obj at the top of the function, you may have saved non-trivial CPU time required to initialize said object, in case i was not equal to 0.

Other than the considerations above, I am of the opinion that if you have to struggle to remember which variables you declared at the top, your function is too long anyway. But it's all semantics.

PO
 
Thanks!

As of today, I have begun to declare variable when:

1) there is something to initialize it with

int x = ...functure return, something added/subtract, etc, to other variables

2) right before its usage

int x = 3;
cout << x;

The only time I declare a variable at the top:

int x = 0;

is when it will be referenced to.

function(int &aboveX)
cout << aboveX;

So aboveX is a reference to x.

I began learning and practicing C++ about four months ago. I find something really interesting. I find that when you first learn C++ in college and reading beginner C++ books, the professor and author typically recommend declaring variables right at the top. They make it like it is imperative that we do that or the program may not work. Now, I feel that the programmer is in control of the program and that he/she can declare variables wherever is appropriate. As I mentioned, I feel it is much easier to recognize variable when the program declare them accord to the examples above.

Kuphryn
 
There are a few benefits declaring local variables near the top of the function.

It encourages you to think about what you will need to use before start coding.
And that is a good thing.

Also, by concentrating all the variable declaration in one place, it is easier to notice
when the list of local variables is growing too long. (may be it is time to split the
function?)

And PeterB touches a great point: if the function is too long, and it becomes difficult to backtrack and figure out the variable type.

It can possibly forces programmers to use Hungarian Block.

But I feel that if a function is so long that it doesn't fit into one or 2 screens, I believe it is wiser to split the function. In languages where local variables must be declared ahead of time, such as Eiffel, programmers tend to write shorter functions because of that reason.

Of course, this touches style issue and is subject to great debates.

Regarding performance cost, suppose for large objects, one can also allocate by heaps, thus delaying the instantiation until very last moment. So the performance
advantage can be maintained. Is this correct?
 
I like C89, where declarations have to appear at the top. (I believe C99 is like C++ in this respect, though I forget if gcc allows this yet.) I figure, if your function is over a page long anyways (50 lines), it's too big. But yes - always keep declaration as close to usage as possible, and limit its scope as much as possible.
--
Stephan T. Lavavej
http://stl.caltech.edu
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
code:<HR>
Code:
This is one aspect of coding I'm pretty lazy with.  When I'm actually thinking and/or working on "production" code, I more or less follow Peter's guideline except when it would cause a variable to be unnecessarily allocated & deleted several times.  A good example would be the scope given to x in <i>for(int x=0; x<q; ++x)</i> - large enough that it's not created Q times, small enough that the compiler will bork if you screw up & use it where you shouldn't.<P><P>Thank God for the variable-type Tooltips in VS.NET...
WTF was wrong with that, OpenTopic? :rolleyes:

Anyway, back on topic... Just to be clear, Kuphryn, my for-loop was just an example of good scoping, namely "close to usage, but not too close." I.e., it's not that it matters at all for that loop (like others have said, it doesn't need to be constructed), but the principle becomes meaningful once you start dealing with more complex scenarios.

code:<HR>
Code:
for (Object myObject; myObject.someCondition; myObject.doSomething())
...will avoid a lot of overhead compared with...
code:<HR>
Code:
while (!timetoexit)
{
  // Declare myObject immediately before we use it
  Object myObject;<P>  ...<P>  if (myObject.someCondition) timetoexit = true;
}

Ok, stupid example. This next compile-time error will probably happen to you at some point, however; being more moderate in the "declare right before you use" principle would've avoided it.

code:<HR>
Code:
void Example(void)
{
  bool someCondition;<P>  ...<P>  if (someCondition)
  {
    // Declare right before usage
    int x;
    doSomething(x);
  } else { 
    // ditto (or not, depending on how functional your brain is)
    int x;
    doSomethingElse(x);
  }<P>  cout << x;   // compiler error
}
 

htom

Ars Legatus Legionis
12,590
Subscriptor
That shouldn't be a compiler error; that's a user scope error or multiple definition error, caught by the compiler (well, caught by some compilers; if there's an "x" in a higher scope you may be SOL.)

I prefer them at the top, regardless of language, where I can find them; then the optimizer can float them to where ever it thinks is appropriate. Saves lots of mind confusion about the nesting scopes.

I've never really seen a language that had

with declare variable name
begin
...
end name

but it would be a great teaching tool, at least.
 
I prefer them at the top, regardless of language, where I can find them; then the optimizer can float them to where ever it thinks is appropriate.
No it can't.

Classes can't be instantiated "wherever". Instantiating a class can have a side-effect, such that:
Code:
MyClass theClass;
doSomething();
is different from:
Code:
doSomething();
MyClass theClass;

Whilst the stack space always gets allocated at the same time (when the function is called), the instantiation of class happens when you tell it to, and the compiler can't optimize that decision. If you declare the thing at the top, it'll get instantiated at the top, and if you then have to exit the function early (before you bother using it), you've wasted that time.
 

htom

Ars Legatus Legionis
12,590
Subscriptor
I put that kind of thing down as another reason not to use c++.

To my way of thinking, the compiler should treat that as either a multiple declaration (if there was previously a MyClass in scope) or a "floatable" declaration, and move it to where it's best put -- which would be where it would be needed, with its destructor moved accordingly.

We're not trying to declare a persistant global, are we? Tsk, tsk.
 
Originally posted by htom:
I put that kind of thing down as another reason not to use c++.
:confused:

Why?

Because the compiler does what you tell it to do?

To my way of thinking, the compiler should treat that as either a multiple declaration (if there was previously a MyClass in scope)
How and why should it do that?

or a "floatable" declaration, and move it to where it's best put -- which would be where it would be needed, with its destructor moved accordingly.
That would be completely stupid. Like I said, changing where the thing is constructed can alter how the program runs. The compiler should construct the object where I say to construct it.

We're not trying to declare a persistant global, are we? Tsk, tsk.
Er... no.
 
That would be completely stupid. Like I said, changing where the thing is constructed can alter how the program runs. The compiler should construct the object where I say to construct it.
hehe. Peter, have you ever written a compiler? If not, you should try it...it's...fun. There's reasons for every single compiler behavior that people don't understand...even if doesn't make sense to you.

As for me, I always declare at the top, because I often find myself going C-->C++ and even C++-->C, my routines are always wickedly short(like they're supposed to be, with function/method call overhead supplantable by inlining), and even if they were long I don't feel like looking through a bunch of random code to find the declaration...but that's just the code I write and how I was raised.

But I do have a question...if people are worried about the lifetime of a particular object inside a subroutine, er...why isn't THAT an object that you dynamically allocate. new and delete exists for a reason, no?

I was always told/always read any person that uses static variable allocation and complains about variable lifetime in a routine is patently misusing static variable allocation. To me, that makes sense. Declaring variables late(especially when some compilers will look through the code and act as if all variables are declared at the top anyway) doesn't.

I will say one thing, though. This programmer's forum is cool because I get to see all the different styles everybody has and conventions people use. Well that, and the fact that I seem to have found yet-another-issue PeterB and I don't agree on...and let's face it...you can never have too many of those.) :)
 
Originally posted by DigitalFury:
hehe. Peter, have you ever written a compiler? If not, you should try it...it's...fun. There's reasons for every single compiler behavior that people don't understand...even if doesn't make sense to you.
No, I haven't. But I know that the compilers I use don't construct objects until they notionally reach the line that constructs that object. So which behaviour is there that people don't understand?

But I do have a question...if people are worried about the lifetime of a particular object inside a subroutine, er...why isn't THAT an object that you dynamically allocate. new and delete exists for a reason, no?
Yes, they do. But allocating memory on the heap/free store is [relatively] slow. If I can allocate it on the stack and defer construction until it's needed, there's no good reason to stick it onto the heap/free store instead.

Anyway -- who's worred about the lifetime of the object? I'm certainly not; I know when the construction overhead occurs, I know how long the thing lives. What's the issue?

I was always told/always read any person that uses static variable allocation and complains about variable lifetime in a routine is patently misusing static variable allocation. To me, that makes sense. Declaring variables late(especially when some compilers will look through the code and act as if all variables are declared at the top anyway) doesn't.
None of the compilers I use do that; they call the constructor only if and when it's needed. They couldn't get away with doing anything else.

As such, I'm at a loss to see why I would bother creating such things on the heap or free store. There's no real advantage in so doing, except for the difference in stack space between the object and the pointer to the object, and a definite disadvantage (it's slower).
 
No, I haven't. But I know that the compilers I use don't construct objects until they notionally reach the line that constructs that object. So which behaviour is there that people don't understand?
Why a compiler might hoist your declaration to not exactly where you instantiate it.

Yes, they do. But allocating memory on the heap/free store is [relatively] slow. If I can allocate it on the stack and defer construction until it's needed, there's no good reason to stick it onto the heap/free store instead.
But that's the point. With some compilers you don't. Heck, some people around here are in the process of writing a compiler/assembler for an embedded system where the memory is hybrid ram/flash, and since the flash is not suitable for random access, they're having to find a way to hoist all data into the top 2Kbytes which are /just/ RAM. For logistical reasons, that means not allowing define-double-words everywhere, and doing per routine allocations at the top of the DS for various technical reasons. Glad it's not my project, but I do know why they're making such restrictions/simplifications of hoisting data creation to the top(er....bottom) of memory.

Anyway -- who's worred about the lifetime of the object? I'm certainly not; I know when the construction overhead occurs, I know how long the thing lives. What's the issue?
Just that not everybody is using MSOC on Windows, even if you are. There's also some oddball stack-management mechanisms on some oddball platforms I've seen make stack-based variables not have quite the performance advantage over heap-stuff of whence you speak. On x86, though...yeah, I see your point.

As such, I'm at a loss to see why I would bother creating such things on the heap or free store. There's no real advantage in so doing, except for the difference in stack space between the object and the pointer to the object, and a definite disadvantage (it's slower).
Well, Peter, if you disambiguate memory references you can cache the data for the dynamically allocated object in your registers or even rename registers. Not everything with pointers is a bad thing...it's just ambiguous pointers that are a problem. Let's not act like disambiguating them in a simple routine that doesn't return a pointer is as simple as making sure the pointer doesn't appear on the right hand side of an assignment. Who couldn't write the parser for that in an afternoon?
 
Originally posted by DigitalFury:
Why a compiler might hoist your declaration to not exactly where you instantiate it.
I would speculate that if it constructed somewhere other than where I coded it to construct then it would cease to be "C++", at which point it's beyond the scope of this thread.

But that's the point. With some compilers you don't. Heck, some people around here are in the process of writing a compiler/assembler for an embedded system where the memory is hybrid ram/flash, and since the flash is not suitable for random access, they're having to find a way to hoist all data into the top 2Kbytes which are /just/ RAM. For logistical reasons, that means not allowing define-double-words everywhere, and doing per routine allocations at the top of the DS for various technical reasons. Glad it's not my project, but I do know why they're making such restrictions/simplifications of hoisting data creation to the top(er....bottom) of memory.
Declaring in the middle versus at the top doesn't alter when (or where) the memory is allocated, merely when the object is constructed into that memory.

Just that not everybody is using MSOC on Windows, even if you are.
It's not unique to that particular compiler. AFAIK, there's not a lot of scope for flexibility in how this works. Calling the constructor can't happen until you've coded it to happen.
 
Stoffel posted something interesting. He responded to this same question and said:

"All memory for all variables in a function are allocated at the beginning of a function in a single step, period. You cannot allocate new stack variables in the middle of a function."

http://www.gamedev.net/community/forums/topic.asp?topic_id=71967

Is that a true statement?

Kuphryn
 
I would speculate that if it constructed somewhere other than where I coded it to construct then it would cease to be "C++", at which point it's beyond the scope of this thread.
Of course it's not strictly C++. So is pretty much everything else not standards compliant that people do all the time.

Declaring in the middle versus at the top doesn't alter when (or where) the memory is allocated, merely when the object is constructed into that memory.
Okay, but at least one of the things people claim about restricting variables to scopes inside of functions is to reduce unnecessary memory footprint. If the memory is allocated at function start(for whatever reasons), your memory footprint stays the same.

It's not unique to that particular compiler.
Never said it was.

AFAIK, there's not a lot of scope for flexibility in how this works.
You'd be surprised. Just like templates, everybody seems to have their own take on how to do things...especially in systems with more restrictive management structures than your typical Windows PC.

Calling the constructor can't happen until you've coded it to happen.
Yes, but like you said, the alloc itself and the constructor call are two different things. And as such, my question would be, if the alloc happens at the beginning of the function on a particular system, what difference does it make whether the variable is declared at the beginning of the routine instead of later? Scope? Access? Um, so what? It's not like the programmer doesn't actually write the code. It's a simple matter to just not write it in such a way that you don't access variables where you shouldn't...or if it were too serious, you just use dynamic allocation.
 

Tristram

Ars Scholae Palatinae
1,428
Subscriptor
Scott Meyers had a point in one of his books that said (I'm paraphrasing) 'Prefer to defer declaration unitl you have a useful value.' His main point was that doing otherwise may lead to Default Constructor and Assignment call, intread of having only one constructor call. Not a hard and fast rule, but, like using ++i; instead of i++; it can make a difference in the lifetime cost of the program.

A side benefit is that it improves logical locality of reference, which may help uderstanding the code.

I prefer locating them as close as I can to use, but in many ways this is personal preference.
 
Originally posted by DigitalFury:
Okay, but at least one of the things people claim about restricting variables to scopes inside of functions is to reduce unnecessary memory footprint. If the memory is allocated at function start(for whatever reasons), your memory footprint stays the same.
Yes, it does. The scope restriction only happens at the C/C++ level -- on entering the function, memory for all stack variables is allocated, no matter where within the source code the variables are declared.

There *might* be a memory saving if initializing the object then goes on to allocate more memory, but that's by no means guaranteed.

You'd be surprised. Just like templates, everybody seems to have their own take on how to do things...especially in systems with more restrictive management structures than your typical Windows PC.
The only possible implementations are:
(1) allocate stack memory on function invokation, initialize object when coded to do so
(2) both allocate stack memory and initialize the object when coded to do so

Anything else would be broken. The latter seems rare (though not impossible), the former seems to be consistently used.

Yes, but like you said, the alloc itself and the constructor call are two different things. And as such, my question would be, if the alloc happens at the beginning of the function on a particular system, what difference does it make whether the variable is declared at the beginning of the routine instead of later? Scope? Access?
The cost of initialization is not zero. If your object is expensive to initialize, there's no point initializing it at the top of the function if you're going to exit early and never end up using it.

Um, so what? It's not like the programmer doesn't actually write the code. It's a simple matter to just not write it in such a way that you don't access variables where you shouldn't...
It's an even simpler matter to make it impossible to access variables you shouldn't access. The topic is about leveraging language features to make it harder to write errors. There's no risk of accessing a variable before it's initialized if you don't declare it until you can initialize it.

or if it were too serious, you just use dynamic allocation.
Which doesn't really solve the problem -- it only serves to reduce the stack usage.
 
Okay, but at least one of the things people claim about restricting variables to scopes inside of functions is to reduce unnecessary memory footprint. If the memory is allocated at function start(for whatever reasons), your memory footprint stays the same.
I think you can still have savings. Take something like this:
code:<HR>
Code:
for (int i = 0; i < 10; ++i)
{
    BigClassA aBCA;
    // Do something with the object
}
for (int i = 0; i < 15; ++i)
{
    BigClassB aBCB;
    // Do something with the object
}
Here, thanks to scope restriction, both objects could potentially share the same stack space. I don't know if any compilers do this, but it should be ok since both objects can't be in use at the same time. This could result in significant stack space savings.
 

htom

Ars Legatus Legionis
12,590
Subscriptor
3) allocate stack on invocation, allocate others and inititalize to "bad data", initialize to "good value" when told to.

4) allocate those known to need stack space on invocation, allocate objects initialized "bad", make good initializations as called for, allocate other stack space as needed.

5) allocate nothing until called for during execution (especially tempting for a function that might run with all variables in registers.)

6) ...

Allocations of anything, things, or nothing between items or objects is not the programmer's concern; he's not supposed to access that space at all. That she thinks (the address of b) - 4 is the address of a (which it may well be sometimes because of the order of declaration) is very bad coding for her to use. If she wants that address dependency, she should tie them into a struct. The textual listing of declarations is not a struct.

Good compilers can be at least as tricky as assembly language programmers, and they have better memories.

"How did it find and generate that!" has been heard coming from more than one pleased compiler writer's lips when looking at the output of his compiler.
 
Originally posted by htom:
3) allocate stack on invocation, allocate others and inititalize to "bad data", initialize to "good value" when told to.

4) allocate those known to need stack space on invocation, allocate objects initialized "bad", make good initializations as called for, allocate other stack space as needed.

5) allocate nothing until called for during execution (especially tempting for a function that might run with all variables in registers.)
These are all the same as (2), as far as I can see, except the fifth; yes, it could run with zero stack and all variables in registers (and if it were going to use a variable repeatedly, it could, in principle, make sure to keep it in a register and never give it stack storage). Though I would imagine that it would make instantiating the object difficult if that were done for anything other than a basic type or POD.
 

htom

Ars Legatus Legionis
12,590
Subscriptor
3) allocates and initiallizes everything at function start. It re-initializes as called for.

4) allocates at startup those known to need memory space; depending on program flow, some locals may need to be allocated, or can be reused, later. ie

int a, b, c ...

do something using a that needs an unregisterable lhand reference

if {compile time undecided} then
do something very complicated using b and c ;
allocate these (to the stack or heap, as appropriate;
if a is not further used, allocate c and use a for b)
remove b and c (but see below)
else {common case}
do something with a
do something with b that can be done in a register
don't use c
endif

remove a, b, and c as appropriate.
 
Originally posted by htom:
3) allocates and initiallizes everything at function start. It re-initializes as called for.
Which is no good. You can't initialize the objects more than the number of times specified in the code (though you can do it fewer times, if the path that executes them is never taken).

4) allocates at startup those known to need memory space; depending on program flow, some locals may need to be allocated, or can be reused, later. ie

int a, b, c ...

do something using a that needs an unregisterable lhand reference

if {compile time undecided} then
do something very complicated using b and c ;
allocate these (to the stack or heap, as appropriate;
if a is not further used, allocate c and use a for b)
remove b and c (but see below)
else {common case}
do something with a
do something with b that can be done in a register
don't use c
endif

remove a, b, and c as appropriate.
Which is like (2) except you remove them too.
 

htom

Ars Legatus Legionis
12,590
Subscriptor
3) Assumes that allocation and initialization are separatable; I'm not a c++ compiler writer, but my impression is that that is allowable. Allocation is a one-time thing; there's no reason that an allocated thing can't be first initiallized as "bad", and then later re-initialized with whatever the programmer calls for as initial data. Initiallization, while conceptually done at allocation or instantiation, can be done at any point before first use, and need not be done at all if the object will not be accessed. (Frequently there's a self-referential aspect to allocation that forces the initiallization not to be delayed, but I don't know that it's always required.)

4) Well, they're all "like", in that they all can be implementations of the same code. This one has the stack size sometimes increasing during the execution of the function, which is different than the others.
 
Originally posted by htom:
3) Assumes that allocation and initialization are separatable;
They are, necessarily. "Allocation" is merely allocating memory. "initialization" is running a constructor; this can do all sorts of things, it's a function call. It could, say, load a driver, then dial up your connection to the Internet, then draw a window on screen. Allocation only allocates a block of memory so that you can have a <span style="font-family: 'Lucida Console', monospace;">this</span> pointer.

I'm not a c++ compiler writer, but my impression is that that is allowable.
My impression is that it's unavoidable.

Allocation is a one-time thing; there's no reason that an allocated thing can't be first initiallized as "bad", and then later re-initialized with whatever the programmer calls for as initial data.
No, it can't. How can you tell the constructor "initialize this object in a bad way"? I certainly don't write anything like that (though I'll grant you, in debug builds my compiler initializes all memory to I think 0xfeeefeee or something like that -- but it doesn't initialize any objects). Initialization is only performed when the code notionally reaches the line where you call the constructor; this is independent of when the allocation occurs (which can be at any time up to that call of the constructor).

Initiallization, while conceptually done at allocation or instantiation,
In the source, yes, in the compiled code, no. They're readily separated. Perhaps even necessarily; even if the constructor fails (throws an exception) the memory is still allocated.

can be done at any point before first use, and need not be done at all if the object will not be accessed.
It can't be done "at any point". Initialization can only occur at the point which represents the call to the constructor. It can't initialize at any other time, because the constructor might have side-effects.

(Frequently there's a self-referential aspect to allocation that forces the initiallization not to be delayed, but I don't know that it's always required.)
Nope, allocation is merely incrementing the stack pointer or getting a block from the heap. It has no dependence on initialization.

4) Well, they're all "like", in that they all can be implementations of the same code. This one has the stack size sometimes increasing during the execution of the function, which is different than the others.
No it isn't. It's like my (2). Unles you're propsing to allocate the stack memory at some random time between the top of the function and the initialization of that object, rather than immediately prior to initialization.
 

htom

Ars Legatus Legionis
12,590
Subscriptor
Yes. Some objects will have known lifetimes that extend throughout the function call; these are "best" allocated at function startup. Others might exist only for (say) the latter half; they can re-use stack space that can be abandoned by those that died before these come into use (this may call for displacement of initializations, insertions of unaccessed dummies for future alignments, ....) Still others might come into existance and disappear, or never appear at all (variables accessed only during a branch not taken; these can be allocated and initialized at the beginning of that branch, destroyed at the end; an optimizer won't (///// shouldn't!) allow such things to be done in a loop.)

You can do a "dummy initialization" or "pseudo instantation" (which does not run the user's code and so does not have those user desired side-effects) but which will effectively drag properly aligned storage space into the cache for future accesses, tagging it as "invalid data" so that a read reference before the user's initialization raises the proper exemption.
 
Originally posted by htom:
Yes. Some objects will have known lifetimes that extend throughout the function call; these are "best" allocated at function startup. Others might exist only for (say) the latter half; they can re-use stack space that can be abandoned by those that died before these come into use (this may call for displacement of initializations, insertions of unaccessed dummies for future alignments, ....)
You can't displace initializations. Initializations must occur in the order in which the programmer wrote them to occur, or else the programmer can no longer guarantee that their fucking program will work.

I don't see what's so complicated about this. Initialization of objects must occur when the programmer says initialization is to occur. It can't be deferred or performed ahead of time.

Still others might come into existance and disappear, or never appear at all (variables accessed only during a branch not taken; these can be allocated and initialized at the beginning of that branch, destroyed at the end; an optimizer won't (///// shouldn't!) allow such things to be done in a loop.)
Sure, but this is no different from the second mechanism I outlined.

You can do a "dummy initialization" or "pseudo instantation" (which does not run the user's code and so does not have those user desired side-effects)
Which isn't initialization/instantiation at all.

but which will effectively drag properly aligned storage space into the cache for future accesses, tagging it as "invalid data" so that a read reference before the user's initialization raises the proper exemption.
If that happens then either the user or the compiler has written what's effectively a bug.
 

Liam

Ars Scholae Palatinae
618
Kuphryn, to answer your initial question: I agree with those who have mentioned that declaring your variables at the very beginning of your function helps you think about their necessity. I also agree with those who would caution you to delay the variable declaration until you can initialize it with something specific (I am a very agreeable person!). I therefore tend to use the following guidelines: if a variable's _intended lifetime_ (not necissarily the scope) extends for the entire function, or if it is used in several places not immediately next to each other, declare it at the top. In this way, the declaration can be guaranteed not to be lost amongst code. If a variable's intended lifetime is very short (e.g. a loop index), declare it only right when you need it. This saves you from seeing "int i,j,k" at the top of your function; they don't really become relavent until you actually get to the loops.

Above all else, be aware of the scope of your variables, and the use of constructors when instantiating classes. Perhaps, as mentioned, you don't want to call the default constructor (or there isn't one available). In this case, feel free to delay your declaration until you have something to initialize it with, even if this violates guideline #1. I'm definitely a member of the "there are no hard-and-fast rules" school of programming style, but it's certainly nice to have guidelines.

Just my personal coding preference. Some of you may be glad you don't have to maintain my code, because I'm some kind of freak who doensn't like Hungarian letters hanging off my variable names and doesn't declare all his variables in one place.
 
Status
Not open for further replies.