Sams Teach Yourself C++ in 21 Days

(singke) #1
declares IntegerArrayto be an array of five integers. It assigns IntegerArray[0]the
value 10 ,IntegerArray[1]the value 20 , and so forth.
If you omit the size of the array, an array just big enough to hold the initialization is cre-
ated. Therefore, if you write
int IntegerArray[] = { 10, 20, 30, 40, 50 };
you will create the same array as you did in the previous example, an array that holds
five elements.
You cannot initialize more elements than you’ve declared for the array. Therefore,
int IntegerArray[5] = { 10, 20, 30, 40, 50, 60};
generates a compiler error because you’ve declared a five-member array and initialized
six values. It is legal, however, to write
int IntegerArray[5] = {10, 20};
In this case, you have declared a five-element array and only initialized the first two ele-
ments,IntegerArray[0]and IntegerArray[1].

414 Day 13


DOlet the compiler set the size of initial-
ized arrays.
DOremember that the first member of
the array is at offset 0.

DON’Twrite past the end of the array.
DON’Tget goofy with naming arrays.
They should have meaningful names just
as any other variable would have.

DO DON’T


Declaring Arrays ............................................................................................


This code uses “magic numbers” such as 3 for the size of the sentinel arrays and 25 for
the size of TargetArray. It is safer to use constants so that you can change all these val-
ues in one place.
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 myCatsat the same time.
In addition, when declaring the number of elements, in addition to using literals, you can
use a constant or enumeration. It is actually better to use these rather than a literal num-
ber because it gives you a single location to control the number of elements. In Listing
13.2, literal numbers were used. If you want to change the TargetArrayso it holds only
Free download pdf