share
Stack OverflowWhere do you declare variables? The top of a method or when you need them?
[+36] [25] Blankman
[2008-11-25 21:31:07]
[ coding-style variables ]
[ http://stackoverflow.com/questions/318943] [DELETED]

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?

[+115] [2008-11-25 21:36:11] James Curran [ACCEPTED]

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

[1] http://en.wikipedia.org/wiki/RAII

dang, can't do +3 - Marcin
Also, it often allows you to initialize them at the declaration point for fewer bugs. - Darron
+1 was going to say the same - Robert Gould
(2) 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
+1 here, but also what Gamecat Said "If the list gets long, it is a sign that the method does too much work so you need to split it in two." - Binary Worrier
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
Keeping things together is also much more readable, and it makes it easier to clean up unused variables when refactoring. - Rolf
1
[+27] [2008-11-25 21:34:08] cagcowboy

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.

Not all languages have this feature, but you have a point ;-). - Gamecat
My company (using C++) has a policy of enclosing variables used in only a small part of the function in braces, giving them their own scope. At first I hated this practice, but it has grown on me as a way of organizing code. I think they started doing it due to a few methods that got a bit long... - rmeador
(4) Variables that are used throughout the function will automatically get declared at the top. You don't need a special case for that. ;) - jalf
rmeador.. I work at a place that does the oppisit. I do it but sometimes I get kick back.. I then point them to code complete (a book they purchased for me) - baash05
(1) "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
2
[+22] [2008-11-25 21:33:13] Gamecat

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.


I would agree with this. - Huntrods
(1) Agree with splitting; disagree with top. +1 anyway. - strager
3
[+13] [2008-11-25 21:37:50] Roddy

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

I generally write short methods so it is pretty moot. The iterator i is a poor example in my opinion. - Tim
I disagree that an iterator is a poor example. There are frequent situations where more than one iterator is required in a given method, nested or otherwise. Which is a situation where badly managed variable scope can get in the way of code readability. - Steve Brouillard
(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
4
[+8] [2008-11-25 21:33:22] Grant Wagner

Yes, declare them when you need them.


Supported by Code Complete. Steve Mcconnell considered the life of a variable in a method a type of scope, and all variable management is an exercise of reducing scope to its logical limit. - Corbin March
If you get the chance I'd say read the book.. Mind you do it while on vacation. The ideas stack up on themselves. - baash05
5
[+8] [2008-11-25 21:36:39] Rob Cooper

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.


6
[+7] [2008-11-25 22:17:06] jalf

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.

No - C never required them all at the beginning of the function; they did, however, have to appear at the beginning of some block. - Jonathan Leffler
Thanks for the correction. Fixed :) - jalf
I don't see why using trash variable like 'i' for distinct for-loops is confusing. - Lance Roberts
Reusing the same variable, you mean? It makes it harder for the compiler to optimize your code, and it may make it harder to read for humans as well (When outside the loop, where was the last assignment to i, and what is its value now?).Not a huge issue, but why not just declare it where it's used? - jalf
7
[+6] [2008-11-25 21:35:16] j0rd4n

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.


8
[+5] [2008-11-25 21:38:51] Kristopher Johnson

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


9
[+4] [2008-11-25 22:31:16] Adam Kahtava

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 just want to give this answer myself. Why isn't that upvoted more often?!? - Tim Büthe
10
[+3] [2008-11-25 21:45:50] ojrac

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.


11
[+3] [2008-11-25 23:12:06] Brian Behm

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.


12
[+2] [2008-11-25 21:40:54] bradheintz

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


13
[+2] [2008-11-25 22:19:59] Perpetualcoder

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!


Methods shouldn't be long enough to have a "top" - Binary Worrier
14
[+1] [2008-11-25 21:37:09] Brian

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.


15
[0] [2008-11-25 21:36:28] Chris Kloberdanz

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.


(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
Same is true of the ANSI C version of the K&R book. C didn't allow variable declarations anywhere else until C99, and I don't think there is a K&R edition for that. - Kristopher Johnson
16
[0] [2008-11-26 00:02:39] McWafflestix

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.


17
[0] [2008-11-26 00:37:31] tomjedrz

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!


18
[0] [2008-11-26 04:59:34] rev

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


(2) Not true since C99 standard was adopted. - Kristopher Johnson
19
[0] [2008-11-26 12:47:14] J.T. Hurley

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.


20
[0] [2008-11-30 12:25:17] Dennis Cheung

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.


21
[0] [2008-12-01 18:17:49] John MacIntyre

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.


22
[0] [2008-12-01 22:05:13] Paul Nathan

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.


23
[0] [2008-11-25 22:36:58] Atømix

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.


24
[0] [2008-11-25 22:40:00] Joachim Sauer

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.


25