Declaring variables in the middle of a routine...

geneb

New member
Joined
Mar 19, 2008
Messages
4
Programming Experience
10+
I've noticed recently that more and more code snippets include variable declarations that happen in the middle of routines. Does this practice have any advantage over declaring all the needed variables at the beginning of a subroutine or function?

thanks all.

g.
 
I prefer to declare the variable when I need it, when the value is assigned if possible. This usually give cleaner and readable code. Using the narrowest scope is better OOP programming practice.
 
I do a mix of both, but one thing that is always absolute (with me) is that I declare all needed variables for a loop before the code enters the loop
 
According to Hoyle:

Robust Programming
The narrower the scope of a variable, the fewer opportunities you have for accidentally referring to it in place of another variable with the same name. You can also minimize problems of reference matching.

Security
The narrower the scope of a variable, the smaller the chances that malicious code can make improper use of it.

How to: Control the Scope of a Variable
 
xoggoth, I tend to agree with you. I cut my teeth on 6502 assembly and K&R C under CP/M. :)

I consider myself an old dog that likes learning new tricks. *laughs*

I did manage to forget ALL my COBOL knowledge though. :)

g.
 
Cobol. Pah! All the best old gits have forgotten PL1 or Algol 66!!

Seriously, the point about not declaring in loops above is good, I would extend that a little to declaring anything used over and over in functions/subs of a class, a form say, once at top. Saves all the news and disposes.

I am fortunate in working for myself now and not having to follow (yech!) standards.
 
I used to have a VAX 8250 with 4 RA81 disk drives and a TU81+ 9 track tape drive set up in an upstairs bedroom. That's got to count for something. :)

I agree on the loop issue - that's just common sense.

Fortunately, I'm at the top of the food chain where I'm at so I do the defining, not the following of standards. :)

g.
 
Back
Top