< Previous | Contents | Next >
It’s often a good idea to define a constant for the number of elements in an array. That’s what I did with MAX_ITEMS, which represents the maximum number of items the hero can carry:
const int MAX_ITEMS = 10;
You declare an array much the same way you would declare any variable you’ve seen so far: You provide a type followed by a name. In addition, your compiler must know the size of the array so it can reserve the necessary memory space. You can provide that information following the array name, surrounded by square brackets. Here’s how I declare the array for the hero’s inventory:
string inventory[MAX_ITEMS];
The preceding code declares an array inventory of MAX_ITEMS string objects. (Because MAX_ITEMS is 10, that means 10 string objects.)
Tric k
You can initialize an array with values when you declare it by providing an initializer list—a sequence of elements separated by commas and surrounded by curly braces. Here’s an example:
string inventory[MAX_ITEMS] = {"sword", "armor", "shield"};
The preceding code declares an array of string objects, inventory, that has a size of MAX_ITEMS. The first three elements of the array are initialized to "sword", "armor", and "shield".
If you omit the number of elements when using an initializer list, the array will be created with a size equal to the number of elements in the list. Here’s an example:
string inventory[] = {"sword", "armor", "shield"};
Because there are three elements in the initializer list, the preceding line creates an array, inventory, that is three elements in size. Its elements are "sword", "armor", and "shield".