< previous page page_636 next page >

Page 636
for (counter = 0; counter <= 100; counter++)
    cout << line[counter];
This example is easy to debug; 101 characters get printed instead of 100. The loop test should be counter < 100. But you won't always use a simple For statement in accessing arrays. Suppose we read data into the line array in another part of the program. Let's use a While statement that reads to the newline character:
counter = 0;
cin.get(ch);
while (ch != '\n')
{
    line[counter] = ch;
    counter++;
    cin.get(ch);
}
This code seems reasonable enough, but what if the input contains a line with more than 100 characters? After the hundredth character is read and stored into the array, the loop continues to execute with the array index out of bounds. Characters are stored into memory locations past the end of the array, wiping out other data values (or even machine language instructions in the program!).
The moral is: When processing arrays, give special attention to the design of loop termination conditions. Always ask yourself if there is any possibility that the loop could keep running after the last array component has been processed.
Whenever an array index goes out of bounds, the first suspicion should be a loop that fails to terminate properly. The second thing to check is any array access involving an index that is based on input data or a calculation. When an array index is input as data, then a data validation check is an absolute necessity.
Testing and Debugging Hints
1. When an individual component of an array is accessed, the index must be within the range 0 through the array size minus one. Attempting to use an index value that is not within this range causes your program to access memory locations outside the array.
2. The individual components of an array are themselves variables of the component type. When values are stored into an array, they should either be of the component type or be explicitly converted to the component type; otherwise, implicit type coercion occurs.

 
< previous page page_636 next page >