35

Hi,

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?

113 accepted

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

27

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.
22

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.

13

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);
}
8

Yes, declare them when you need them.

8

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.

7

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.
6

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.

5

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

3

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.

3

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.

2

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 ;-)

2

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!

2

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.

1

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.

0

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.

0

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.

0

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.

0

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.

0

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!

0

if it is C code, you have to declare them at the top.

0

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.

0

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.

0

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.

0

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.