Initializing an Array in C++ - dummies

By Stephen R. Davis

Like any other variable in C++, an array starts out with an indeterminate value if you don’t initialize it. The only difference is that unlike a simple variable, which contains only one undetermined value, an array starts out with a whole lot of unknown values:

int nScores[100];  // none of the values in nScores
                   // known until you initialize them

You can initialize the elements of an array with a loop as follows:

int nScores[100];  // declare the array and then...
for (int i = 0; i < 100; i++) // ...initialize it
    nScores[i] = 0;

You can also initialize an array when you declare it by including the initial values in braces after the declaration. For a small array, this is easy:

int nCount[5] = {0, 1, 2, 3, 4};

Here the value of nCount[0] is initialized to 0, nCount[1] to 1, nCount[2] to 2, and so on. If there are more elements than numbers in the list, C++ pads the list with zeros. Thus, in the following case:

int nCount[5] = {1};

the first element (nCount[0]) is set to 1. Every other element gets initialized to zero. You can use this approach to initialize a large array to zero as well:

int nScores[100] = {0};

This not only declares the array but initializes every element in the array to zero.

By the same token, you don’t have to provide an array size if you have an initializer list — C++ will just count the number of elements in the list and make the array that size:

int nCount[] = {1, 2, 3, 4, 5};

This declares nCount to be 5 elements large because that’s how many values there are in the initializer list.

Arrays are useful for holding small to moderate amounts of data. (Really large amounts of data require a database of some sort.) By far, the most common type of array is the character array.