Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am in sort of a dilemma (in a geekish way of course).

I love to declare variables at the beginning of my methods, and usually order them in some logical way.

The problem is, when the list gets long, it sort of gets out of hand.

Should I just declare them when I need them?

share|improve this question

migrated from stackoverflow.com Mar 10 '11 at 5:48

24 Answers

Variables should be declared as close to where they are used as possible.

share|improve this answer
7  
I couldn't agree more. I hate seeing a pile of variables declared at the top of a method - that's just sloppy. – Jon Tackabury Nov 26 '08 at 13:01
4  
Agree with Binary W - if you have a list of variables in your function so long that you can order them "logically" then it's time to split up your function. – Richard Ev Nov 29 '08 at 11:09
5  
Keeping things together is also much more readable, and it makes it easier to clean up unused variables when refactoring. – Rolf Nov 30 '08 at 12:56
show 4 more comments

My two cents:

  • Declare variables that are used through-out the function at the top.
  • Declare variables that are used in only a small part of the function at the point where they are needed.
share|improve this answer
10  
Variables that are used throughout the function will automatically get declared at the top. You don't need a special case for that. ;) – jalf Nov 25 '08 at 22:18
4  
"Declare variables that are used through-out the function at the top." - I would disagree with that. Always declare variables when they are needed, not before. – Jon Tackabury Nov 26 '08 at 13:03
show 3 more comments

If the list gets long, it is a sign that the method does too much work so you need to split it in two.

Same story with classes and fields.

But I like to put them at the top. Preferably with a piece of comment on their purpose.

share|improve this answer
6  
Agree with splitting; disagree with top. +1 anyway. – strager Nov 28 '08 at 4:42
show 1 more comment

Your local variables should have absolutely no more visibility than required - so declare them when you need them, and let them go out of scope when you're done with them.

The classic case of this is C++ loop variables:

//BAD - old, C-style:
int i;

for (i=0; i < 100; ++i)
{
...
}

.. vs..

//GOOD

for (int i=0; i < 100; ++i)
{
...
}

One benefit of the reduced scope which isn't immediately obvious is that the following code now fails to compile:

for (int i=0; i < 100; i++);
{
  printf("loop %d\n", i);
}
share|improve this answer
1  
++Roddy. This is a great tip. Who has had to go through code where the variable 'i' was used over hundreds (or more) lines of code and multiple loops? I know I have. Another great scope trick (in C++) is pointer variable scope within if statements: if (float* eip = this->getEip()) { /* use eip */ } – justin Nov 30 '09 at 22:48
show 2 more comments

Your variables should have the smallest possible scope allowed by the language. (C used to require all variables to be declared at the beginning of a function block. No sane language requires this, because it is a terrible idea.)

A larger than necessary scope means:

  • The code gets harder to read, because I can't see the variable declarations anywhere near where they're actually used, and vice versa.
  • The code gets harder to optimize for the compiler, because every variable could potentially be used anywhere in the function. If it is declared immediately before use, the compiler can at least easily see that it isn't used before then. And if it is declared in a nested scope in the function (For example inside a loop), the compiler further knows that the variable is not used after the loop either.
  • You get a greater chance of name collisions. (A canonical example might be the 'i' loop iteration variable. If you have two for-loops in your function, they can't both use an 'i' variable, unless either
  • They reuse the same variable (which confuses both the reader and the compiler)
  • One of them use a differently named variable (now you have to declare both 'i' and 'j' at the top of the function.
share|improve this answer
show 4 more comments

I would say that if your methods are so long that you actually need to differentiate between the two, you may want to consider refactoring.

I personally like to keep them close to where they are used, so their purpose is fresh in my head. However, I think this comes down to programmer preference.

share|improve this answer

Yes, declare them when you need them.

share|improve this answer
show 2 more comments

Depends on what language you're using.

Languages like JavaScript do not have block scope. With JavaScript you probably want to declare all your variables used in a function at the start of the function body.

share|improve this answer
show 2 more comments

Declare variables close to where you need them. If your function is getting too long, you probably ought to see if it needs to be refactored into smaller, more specific, functions. Remember, the key is coherent readability of your code.

share|improve this answer

Never declare a variable until the point where you initialize it. This reduces the opportunities to have bugs due to uninitialized variables.

share|improve this answer

I get the sense that declaring variables "at the top" is only a common "style" decision because C90 required it.

Now that you're free to choose, you should probably wait until you need it. Your code should be more readable that way.

share|improve this answer

The orthodoxy on coding clarity is that you should declare near first use. If you're following the other orthodoxy about keeping your function/methods short, though, then any declaration will be near its first use. Problem solved ;-)

share|improve this answer

Right where you need them. That way they may never need to be instantiated if the code branches a different direction and never needs the variable.

share|improve this answer

I suggest declare a variable based on the usage scope. If used throughout the method..top is good..if something like a temporary holder..closest to its usage. In this way you will always declare closest to the usage...don't forget to indent and space out your code for readability.

Cheers!

share|improve this answer
show 1 more comment

I have all my variables declared at the top. I've read through enough code where variables are declared mid-code that I don't want to play "hunt for the declaration" again. While I'm actively working on a function, variables are scattered whereever they are used; once the function works, I take a pass and bring the variables up to the top and do some commenting - "others-ready code", basically.

share|improve this answer

You should in general try to keep them limited to the scope in which they are needed. This fits nicely with the concept of RAII (another answer provided gives a good link for details), and keeps you from having to waste time searching for the declaration of the variable in question.

However, this does not limit you to declaring them at the top or only right where they are used. I view that as an issue of preference for either you or your coding team. With either approach, consistency is key.

share|improve this answer

If I remember correctly the K&R book says to declare a variable close to where you'll be using it. I have done both in practice, though.

share|improve this answer
1  
One problem with that memory - in original K&R C you had to declare your variables at the start of a block. – Paul Tomblin Nov 25 '08 at 21:40
show 1 more comment

Just to add to what has already been said. As a general rule my Methods fit on about one page. If it's getting longer than that, I refactor. That being said, good advice on this page.

share|improve this answer

I usually declare them where they are needed.

But there's a way where you get the best of both worlds: keep your methods as short as they should be (no longer than 10-15 lines). This way the difference won't be too large.

share|improve this answer

I tend to believe that you should allocate variables at the beginning of whatever uses them. If you find yourself declaring variables significantly distant from the beginning of the method where you're using them (unless they're class variables, of course), then I take that as a sign that my method's doing far too much! Really, generally, I try to keep my methods very compact; of course you're going to have variables that get declared in nested scopes, but in general, if I find myself declaring variables far down the method body, I realize that my method is just too damn long.

share|improve this answer

Back in the good-old-days, all variables were declared at the top because the compiler/system needed to account for all of them before doing anything else. That is obviously no longer the case.

My preferences is to ...
a- Declare each variable at the top of the section of code where it is used. If there are too many variable, that is a clue that the section of code can be broker into smaller pieces. I do not like to see declaration statements among the logic; I find they clutter the code and make it harder to understand.

b- Use descriptive names along with a type indicator if it isn't clear, so that it is clear what the variable is and what it is doing. In particular, do this for work variables and variables used for converting things.

Have fun!

share|improve this answer

My personal preference is to place any globals in a block at the top of the code, and place locals as close as possible to their own scope.

share|improve this answer

Declare variable in the beginning of the block.

If it used in only a small part of the function, create a block with { } and declare the variable in the beginning of block. Then I can trace the scope of the variable easily, and GC friendly.

share|improve this answer

I've always been a top-of-the-block kind of guy, but lately, I'm moving to throughout my code. I think it's really an irrelevant personal preference (sincerity intended).

As for all the comments about your long list of variable declarations is an indication you need to refactor your code. This may be the case, but not necessarilly. When your current function design does make sense, you may find that many of those variables might fit nicely into a struct or thier own class. This will help clean up your code a bit.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.