[vox-tech] global variables in C

Jeff Newmiller vox-tech@lists.lugod.org
Fri, 20 Sep 2002 13:10:46 -0700 (PDT)


On Fri, 20 Sep 2002, Peter Jay Salzman wrote:

> 
> ok, first i'd like to apologize for bringing up such a tired subject,
> but i'd like to understand this better.
> 
> 
> conventional wisdom says that you should avoid using globals.
> 
> reading through some C books like the deitel book which is used at UCD
> and SAMS "C primer plus", i find that they don't really address this
> issue at all.  when i talk to people, i hear the same two reasons over
> and over:
> 
> 1. name clashing
> 2. readability
> 
> what i'd like to know is if this is all there is.  are there more
> reasons why we should follow conventional wisdom?  or is this more of a
> guiding principle and not something to be followed blindly?   it seems
> like for some applications, like GUI and multi-thread programming, the
> use of globals can really simplify things a lot.
> 
> please no sarcasm or flames -- just lucid explanations.  i'd like to
> understand this better.

I can't promise lucidity... :)

Not using globals is not a hard and fast rule.  EVERY program uses some
globals... even if only in the underlying runtime.

However, I think the key issue is the number of routines that directly
access those variables.  Having a large amount of code dependent on a
variable makes changing the semantics of that variable's use difficult...
you have a lot of dependent code to examine and possibly change.  Also, it
means many code module compilations depend on one module that contains
that variable, so if you do change it then the recompilation can become a
serious time eater in development (in hundred-thousand-line programs and
up, this is not to be laughed at!).

As for multi-threading... globals can be necessary, but they also couple
the threads.  When one thread starts changing that global, any other
thread needing access has to block... turning a multi-threading program
into an inefficient single-threaded program.  And if you try to turn a
single-threaded program that has non-atomic globals in it into a
multi-threaded program, you may dearly regret thinking globals were a good
idea because it will lack appropriate semantics for blocking reads during
writes.

As for GUI... see my response to Bill.

Never say never to globals... but if you can avoid them you can avoid
numerous problems down the line.  At least try using statics if you think
you need globals.

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil@dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...2k
---------------------------------------------------------------------------