An Ethics Question (global variables)

Herman Rubin cik at l.cc.purdue.edu
Fri Apr 14 01:50:34 AEST 1989


In article <1989Apr7.190827.4289 at utzoo.uucp>, henry at utzoo.uucp (Henry Spencer) writes:
> 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.

			..........................

Why is it necessary to use one or the other?  Consider the following
highly recursive program, which is a fairly quick way of simulating
the number of heads in n tosses of an honest coin.  Please excuse minor
C syntax errors.

external arrays and variables and #includes
coin(n)
int n;
{
SETUP
int m;
m = cn(n);
RESTORE
return m;
}
cn(n)
int n;
{
int k:
if(ODD(n))k=BIT;
else k=0;
n >>= 1;
if (n == 0) return k;
return (k + cn(n) + 2*cn(n-cn(n)));
}

Now SETUP and BIT can be done in many ways; it is even possible to use 
globals outside of the recursion and no fixed registers, but this involves
many memory references at each stage.  On the VAX, the best procedure I have
come up with uses 5 registers, but the recursion passes only one number, and
the average number of memory reference per use of BIT is <0.02.
-- 
Herman Rubin, Dept. of Statistics, Purdue Univ., West Lafayette IN47907
Phone: (317)494-6054
hrubin at l.cc.purdue.edu (Internet, bitnet, UUCP)



More information about the Comp.lang.c mailing list