[Tutor] global variables

Michael Powe michael@trollope.org
Thu Dec 5 02:21:01 2002


On Wed, Dec 04, 2002 at 11:16:26PM -0600, david wrote:
> hello again!
> why are global variables bad?
> what are some examples of global variables 
> causing problems? 

the common reasonings are:  you can change a global from 
any function, so that makes it easy for you to do it
inadvertently.  in a complex program with many functions,
you may lose track of what's happening to a global.  that
makes it difficult to track down bugs related to the variable's
value.  it can mean that you didn't think out your program's 
structure before hitting the keyboard, but just started typing. 
that lack of forethought may mean that your code is going to 
wander all over creation, as you try to account for situations 
you didn't plan for.

you could think of the difference between local and global variables
as the difference between putting things away when you're done with
them and just throwing them down anywhere.  when tools are put away,
they're right there when you need them.  that's your local variables.
when they're left lying around, it turns out your brother-in-law took
off with that wrench you need when he saw it lying on the kitchen
counter, and now he thinks he put it in a box by the tires under your
bench in the garage, but he can't be sure.  that's your global
variables.

there are very few cases when you need a variable to carry values throughout
the life of a program.  if it's not needed, don't do it.  


mp