How to Initialize an Array in C++ - dummies

How to Initialize an Array in C++

By Stephen R. Davis

In C++, a local variable does not start life with a valid value, not even the value 0. Said another way, a local variable contains garbage until you actually store something in it. Locally declared arrays are the same — each element contains garbage until you actually assign something to it.

You should initialize local variables when you declare them. This rule is even truer for arrays. It is far too easy to access uninitialized array elements thinking that they are valid values.

“Local variable” refers to the normal variables declared within a function. C++ purists actually call these automatic variables to differentiate them from static variables.

Fortunately, a small array may be initialized at the time it is declared with an initializer list. The following code snippet demonstrates how this is done:

float floatArray[5] = {0.0, 1.0, 2.0, 3.0, 4.0};

This initializes floatArray[0] to 0, floatArray[1] to 1.0, floatArray[2] to 2.0, and so on.

C++ pads the initialization list with 0s if the number of elements in the list is less than the size of the array. In fact, an empty initializer list can be used to initialize an array to 0:

int nArray[128] = {}; // initialize array to all 0's

The number of initialization constants can determine the size of the array. For example, you could have determined that floatArray has five elements just by counting the values within the braces. C++ can count as well (here’s at least one thing C++ can do for itself).

float floatArray[] = {0.0, 1.0, 2.0, 3.0, 4.0};