if(i==5) { int z=i; printf("%d\n", z); } }
It's always a good idea to declare a variable as close as possible to the place it's used.
Beware though that this was banned in C89, so a strictly conforming compiler would barf on it.
I'm referring to placing the declaration of a variable just inside the block where it is used. i.e. inside the opening brace, as in the example above. That was never illegal - was it? I assume that you're referring to the C++ practise of putting a declaration absolutely anywhere?
Two comments, first you shouldn't have procedures so long that you have to go paging up to find the start of it.
How long do you suggest, then? :o) Seriously, it's been shown that the length of a piece of code does little to affect the readability of it. What affects the readability is the complexity: the number of conditions, loops, variables, etc. A 100 line, drop-through routine which implements e.g. a state machine, is very simple to read. Breaking up a simple piece of code purely on the basis that it's "too long" makes little sense.
And second, to my mind it's much better to have all declarations in one place. If, 50 lines later you see variable z used, where will you look for its declaration?
Hmmm. You're contradicting your first argument! :oP But since I've done that myself, I should answer the point. This is the "principle of proximity" which CS lecturers often refer to: keep related actions together. Keep variable declarations near to where the variables are used; keep comments near the code it refers to, etc. Your point is valid, but it's an unusual scenario. Much more likely is that a variable is not used throught an entire function; use of a variable is much more often isolated to a specific job in a specific part of the code. Putting all variable declarations in one place gives the impression that all the variables are used throughout the whole routine. Another point is that if a variable is declared a long way from where it is used, yes, as you say, you have to go and find it when you need to see its declaration, but also you have a lot of code to search though when you're trying to find where it's been changed. That makes finding bugs harder when you discover the variable isn't containing the value you expect. This problem is especially so someone has been back to modify a piece to older code. -- "...our desktop is falling behind stability-wise and feature wise to KDE ...when I went to Mexico in December to the facility where we launched gnome, they had all switched to KDE3." - Miguel de Icaza, March 2003