C++

Declaring Arrays

Arrays can have any legal variable name, but they cannot have the same name as another variable or array within their scope. Therefore, you cannot have an array named myCats[5] and a variable named myCats at the same time.

You can dimension the array size with a const or with an enumeration. Listing 11.3 illustrates this.

Listing 11.3. Using consts and enums in arrays.

1: // Listing 11.3

2: // Dimensioning arrays with consts and enumerations

3:

4: #include <iostream.h>

5: int main()

6: {

7: enum WeekDays { Sun, Mon, Tue,

8: Wed, Thu, Fri, Sat, DaysInWeek };

9: int ArrayWeek[DaysInWeek] = { 10, 20, 30, 40, 50, 60, 70 };

10:

11: cout << "The value at Tuesday is: " << ArrayWeek[Tue];

12: return 0;

13: }

OUTPUT:

The value at Tuesday is: 30

ANALYSIS: Line 7 creates an enumeration called WeekDays. It has eight members. Sunday is equal to 0, and DaysInWeek is equal to 7.

Line 11 uses the enumerated constant Tue as an offset into the array. Because Tue evaluates to 2, the third element of the array, DaysInWeek[2], is returned and printed in line 11.

Back to Index