Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!purdue!mentor.cc.purdue.edu!l.cc.purdue.edu!cik From: cik@l.cc.purdue.edu (Herman Rubin) Newsgroups: comp.lang.c Subject: Re: An Ethics Question (global variables) Summary: Why not use both at the same time? Message-ID: <1230@l.cc.purdue.edu> Date: 13 Apr 89 15:50:34 GMT References: <1819@uop.edu> <1989Apr7.190827.4289@utzoo.uucp> Organization: Purdue University Statistics Department Lines: 53 In article <1989Apr7.190827.4289@utzoo.uucp>, henry@utzoo.uucp (Henry Spencer) writes: > In article <1819@uop.edu> jeff@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@l.cc.purdue.edu (Internet, bitnet, UUCP)