On Tue, 2003-04-15 at 05:48, Derek Fountain wrote:
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?
No, not as the first line of a block, that's always been legal (I think). I missed that.
I assume that you're referring to the C++ practise of putting a declaration absolutely anywhere?
That is what I was thinking of, yes, but it's not just in c++. In K&R C it was allowed to have things like for (int i = 0; i < 5; i++){ fprintf(stderr, "foo\n"); int a = 3; } and, apparently, that's legal again in C99.
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.
I disagree. I remember from comp.sci. class studies on this type of thing, but I mainly go on personal experience. When I have to make sense of a large program, I find it much simpler if it's subdivided into logically distinct parts (procedures or methods) with well defined purposes. How long? Some people say one screen, but I don't much like reading a lot of code on screen. I prefer no more than one page of paper when it's printed out. If it's much longer, except in extreme circumstances, it's very likely to be poorly written anyway.
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.
I agree that to some extent it depends on the code.
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.
Absolutely, but I feel this is the role of the procedure. With the short procedures I talked about, the first line(s) of the procedure is, I believe, the right place to have variable declarations.
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.
True