|
|
|
|
|
|
|
when i < 0 or when i> 99? The result is that a memory location outside the array is accessed. C++ does not check for invalid (out-of-bounds) array indices either at compile time or at run time. If i happens to be 100 in the statement above, the computer stores 62.4 into the next memory location past the end of the array, destroying whatever value was contained there. It is entirely the programmer's responsibility to make sure that an array index does not step off either end of the array. |
|
|
|
 |
|
 |
|
|
Out-of-Bounds Array Index An index value that, in C++, is either less than zero or greater than the array size minus one. |
|
|
|
|
|
|
|
|
Array-processing algorithms often use For loops to step through the array elements one at a time. Here is a loop to zero out our 100-element alpha array (i is an int variable): |
|
|
|
|
|
|
|
|
for (i = 0; i < 100; i++)
alpha[i] = 0.0; |
|
|
|
|
|
|
|
|
We could also write the first line as |
|
|
|
|
|
|
|
|
for (i = 0; i <= 99; i++) |
|
|
|
|
|
|
|
|
However, C++ programmers commonly use the first version so that the number in the loop test (100) is the same as the array size. With this pattern, it is important to remember to test for less-than, not less-than-or-equal. |
|
|
|
|
|
|
|
|
Assertions can help convince you (and others) that an array-processing loop executes the correct number of times. In assertions written as comments, we often need to refer to a range of array elements: |
|
|
|
|
|
|
|
|
// alpha[i] through alpha[j] have been printed |
|
|
|
|
|
|
|
|
To specify such ranges, it is more convenient to use an abbreviated notation consisting of two dots: |
|
|
|
|
|
|
|
|
// alpha[i]..alpha[j] have been printed |
|
|
|
|
|