The elements of an array
also can be initialized in the array
declaration by following the array
name with an equals sign and a brace-delimited comma-separated list of initializers. The program in Fig. 7.4 uses an initializer list to initialize an integer array
with five values (line 11) and prints the array
in tabular format (lines 13–17).
1 // Fig. 7.4: fig07_04.cpp
2 // Initializing an array in a declaration.
3 #include <iostream>
4 #include <iomanip>
5 #include <array>
6 using namespace std;
7
8 int main()
9 {
10 // use list initializer to initialize array n
11 array< int, 5 > n = { 32, 27, 64, 18, 95 };
12
13 cout << "Element" << setw( 13 ) << "Value" << endl;
14
15 // output each array element's value
16 for ( size_t i = 0; i < n.size(); ++i )
17 cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;
18 } // end main
Element Value
0 32
1 27
2 64
3 18
4 95
If there are fewer initializers than array
elements, the remaining array
elements are initialized to zero. For example, the elements of array n
in Fig. 7.3 could have been initialized to zero with the declaration
array< int, 5 > n = {}; // initialize elements of array n to 0
which initializes the elements to zero, because there are fewer initializers (none in this case) than array
elements. This technique can be used only in the array
’s declaration, whereas the initialization technique shown in Fig. 7.3 can be used repeatedly during program execution to “reinitialize” an array
’s elements.
If the array
size and an initializer list are specified in an array
declaration, the number of initializers must be less than or equal to the array
size. The array
declaration
array< int, 5 > n = { 32, 27, 64, 18, 95, 14 };
causes a compilation error, because there are six initializers and only five array
elements.