
Example 18.1: accessing the members of an array
int ages[J = {49,48,26,l9,l6}; int counter; for (counter = 0, counter < 5, counter++) { cout « ages[counterJ « endl; }
This second usage of the square brackets is as the array notation of dereference or more commonly called the index operator. As an operator it provides the value held by the member of the array. For example, during one of the iterations of the for loop the index (which is an integer data type) will have the value of 3. The expression ages[counter] would in essence be: ages[3]. The dereference operator of means to go the 3rd offset from the front of the ages array and get the value stored there. In this case the value would be 19. The array members (or elements) are referenced starting at zero. The more common way for people to reference a list is by starting with one. Many programming languages reference array members starting at one, however for some languages (and C++ is one of them) you will need to change your thinking. Consider:
Position |
C++ |
Miss America |
Other Contests |
zero offsets from the front |
ages [0] |
Winner |
1st Place |
one offsets from the front |
ages [1] |
1st Runner Up |
2nd Place |
two offsets from the front |
ages [2] |
2nd Runner Up |
3rd Place |
three offsets from the front |
ages [3] |
3rd Runner Up |
4th Place |
four offsets from the front |
ages [4] |
4th Runner Up |
5th Place |
Saying that my cousin is the 2nd Runner Up in the Miss America contest sounds so much better than saying that she was in 3rd Place. We would be talking about the same position in the array of the five fnalists.
Rather than using the for loop to display the members of the array, we could have written five lines of code as follows:
cout << ages[0] << endl;cout << ages[1] << endl;cout << ages[2] << endl;cout << ages[3] << endl;cout << ages[4] << endl;
- 1471 reads