Programming in C

(Barry) #1
Global Variables 155

much improved readability of this program over the equivalent one from Chapter 7 is a
direct result of the structuring of the program into separate functions that perform small,
well-defined tasks. Note that you do not even need comment statements inside the main
routine to describe what the program is doing—the function names speak for them-
selves.
The primary use of global variables is in programs in which many functions must
access the value of the same variable. Rather than having to pass the value of the variable
to each individual function as an argument, the function can explicitly reference the
variable instead.There is a drawback with this approach. Because the function explicitly
references a particular global variable, the generality of the function is somewhat
reduced. So, every time that function is to be used, you must ensure that the global vari-
able exists, by its particular name.
For example, the convertNumberfunction of Program 8.14 succeeds in converting
only a number that is stored in the variable numberToConvertto a base as specified by
the value of the variable base. Furthermore, the variable digitand the array
convertedNumbermust be defined. A far more flexible version of this function would
allow the arguments to be passed to the function.
Although the use of global variables can reduce the number of arguments that need
to be passed to a function, the price that must be paid is reduced function generality
and, in some cases, reduced program readability.This issue of program readability stems
from the fact that if you use global variables, the variables that are used by a particular
function are not evident simply by examining the function’s header. Also, a call to the
particular function does not indicate to the reader what types of parameters the function
needs as inputs or produces as outputs.
Some programmers adopt the convention of prefixing all global variable names with
the letter “g”. For example, their variable declarations for Program 8.14 might look like
this:


int gConvertedNumber[64];
long int gNumberToConvert;
int gBase;
int gDigit = 0;


The reason for adopting such a convention is that it becomes easier to pick out a global
variable from a local one when reading through a program. For example, the statement


nextMove = gCurrentMove + 1;


implies that nextMoveis a local variable and gCurrentMoveis a global one.This tells the
reader of this line about the scope of these variables and where to look for their declara-
tions.
One final thing about global variables.They do have default initial values: zero. So, in
the global declaration


int gData[100];


all 100 elements of the gDataarray are set to zero when the program begins execution.

Free download pdf