Programming in C

(Barry) #1

304 Chapter 13 The Preprocessor


the array—either explicitly or implicitly (by specifying a list of initializers). Subsequent
program statements will likely use the knowledge of the number of elements contained
inside the array. For example, if the array dataValuesis defined in a program as follows:
float dataValues[1000];
there is a good chance that you will see statements in the program that use the fact that
dataValuescontains 1,000 elements. For instance, in a forloop
for ( i = 0; i < 1000; ++i )
...
you would use the value 1000 as an upper bound for sequencing through the elements
of the array. A statement such as
if ( index > 999 )
...
might also be used in the program to test if an index value exceeds the maximum size of
the array.
Now suppose that you had to increase the size of the dataValuesarray from 1,000
to 2,000 elements.This would necessitate changing all statements that used the fact that
dataValuescontained 1,000 elements.
A better way of dealing with array bounds, which makes programs easier to extend, is
to define a name for the upper array bound. So, if you define a name such as
MAXIMUM_DATAVALUESwith an appropriate #definestatement:
#define MAXIMUM_DATAVALUES 1000
you can subsequently define the dataValuesarray to contain MAXIMUM_DATAVALUESele-
ments with the following program line:
float dataValues[MAXIMUM_DATAVALUES];
Statements that use the upper array bound can also make use of this defined name.To
sequence through the elements in dataValues,for example, the forstatement
for ( i = 0; i < MAXIMUM_DATAVALUES; ++i )
...
could be used.To test if an index value is greater than the upper bound of the array, you
could write
if ( index > MAXIMUM_DATAVALUES - 1 )
...
and so on.The nicest thing about the preceding approach is that you can now easily
change the size of the dataValuesarray to 2,000 elements by simply changing the defi-
nition:
#define MAXIMUM_DATAVALUES 2000
Free download pdf