< Previous | Contents | Next >
As you learned, you have to be careful when you index an array. Because an array has a fixed size, you can create an integer constant to store the size of an array. Again, that’s just what I did in the beginning of the program:
const int MAX_ITEMS = 10;
Understanding C-Style Strings 101
In the following lines, I use MAX_ITEMS to protect myself before adding another item to the hero’s inventory:
if (numItems < MAX_ITEMS)
{
}
else
{
}
inventory[numItems++] = "healing potion";
cout << "You have too many items and can’t carry another.";
In the preceding code, I first checked to see whether numItems is less than MAX_ITEMS. If it is, then I can safely use numItems as an index and assign a new string object to the array. In this case numItems is 3, so I assign the string "healing potion" to array position 3. If this hadn’t been the case, then I would have displayed the message, “You have too many items and can’t carry another.”
So what happens if you do attempt to access an array element outside the bounds of the array? It depends, because you’d be accessing some unknown part of the computer’s memory. At worst, if you attempt to assign some value to an element outside the bounds of an array you could cause your program to do unpredictable things and it might even crash.
Testing to make sure that an index number is a valid array position before using it is called bounds checking. It’s critical for you to perform bounds checking when there’s a chance that an index you want to use might not be valid.