|
|
|
|
|
|
|
for (precinct = 0; precinct < 4; precinct++)
{
for (candidate = 0; candidate < 10; candidate++)
cout << setw(4) << votes[candidate][precinct];
cout << endl;
} |
|
|
|
|
|
|
|
|
In the output statement we have specified the array indices in the wrong order. The loops march through the array with the first index ranging from 0 through 9 (instead of 0 through 3) and the second index ranging from 0 through 3 (instead of 0 through 9). The effect of executing this code may vary from system to system. The program may output the wrong array components and continue executing, or the program may crash with a memory access error. |
|
|
|
|
|
|
|
|
An example of the second kind of erroran incorrect index range in an otherwise correct loopcan be seen in this code: |
|
|
|
|
|
|
|
|
for (precinct = 0; precinct < 10; precinct++)
{
for (candidate = 0; candidate < 4; candidate++)
cout << setw(4) << votes[precinct][candidate];
cout << endl;
} |
|
|
|
|
|
|
|
|
Here, the output statement correctly uses precinct for the first index and candidate for the second. However, the For statements use incorrect upper limits for the index variables. As with the preceding example, the effect of executing this code is undefined but is certainly wrong. A valuable way to prevent this kind of error is to use named constants instead of the literals 10 and 4. In the case study, we used NUM_PRECINCTS and NUM_CANDIDATES. You are much more likely to spot an error (or to avoid making an error in the first place) if you write something like this: |
|
|
|
|
|
|
|
|
for (precinct = 0; precinct < NUM_PRECINCTS; precinct++) |
|
|
|
|
|
|
|
|
than if you use a literal constant as the upper limit for the index variable. |
|
|
|
|
|
|
|
|
Testing and Debugging Hints |
|
|
|
|
|
|
|
|
1. Initialize all components of an array if there is any chance that you will attempt to access the entire array. |
|
|
|
|
|
|
|
|
2. Use the proper number of indices with array names when referencing an array component, and make sure the indices are in the correct order. |
|
|
|
|
|
|
|
|
3. Use meaningful identifiers for index variables. |
|
|
|
|
|
|
|
|
4. In array-processing loops, double-check the upper and lower bounds on each index variable to be sure they are correct for that dimension of the array. |
|
|
|
|
|