An Ethics Question (global variables)

Henry Spencer henry at utzoo.uucp
Sat Apr 8 05:08:27 AEST 1989


In article <1819 at uop.edu> jeff at uop.edu (Jeff Ferguson) writes:
>Global variables or passed parameters?  I'm anxiously awaiting the pros
>and cons of this issue.  Thank you.

Parameters are generally better than global variables.  The more restricted
scope gives less opportunity for other parts of the program to modify them
in surprising ways, and the explicit presence in the parameter list makes
it easier to remember who uses what.

Efficiency considerations can go either way, depending on the machine,
although one significant issue is it's generally harder for compilers to
know when it's safe and desirable to put global variables in registers.
On almost any machine, the code will run a good deal faster if heavily-
used variables are in registers.

The down side is that it can be a royal pain passing parameters down
through multiple layers of functions just because they're needed at the
lowest level.  This is especially true if they're used for things like
error reporting that are peripheral to the function's intended purpose;
then the clutter in the argument list obscures the real meaning.  For
this sort of thing, global variables are probably better.

Almost anything that relies on global variables is problematic in the
presence of multiple processes within the same address space (aka threads).
-- 
Welcome to Mars!  Your         |     Henry Spencer at U of Toronto Zoology
passport and visa, comrade?    | uunet!attcan!utzoo!henry henry at zoo.toronto.edu



More information about the Comp.lang.c mailing list