Some aggregates contain other aggregates — for example, arrays of arrays, arrays of structures, or structures that are composed of other structures. Initializers can be supplied for such constructs by initializing each one in the order it occurs with a brace-enclosed list. For example:
// Declare an array of type RCPrompt.
RCPrompt rgRCPrompt[4] =
{ { 4, 7, "Options Are:" },
{ 6, 7, "1. Main Menu" },
{ 8, 7, "2. Print Menu" },
{ 10, 7, "3. File Menu" } };
Note that rgRCPrompt
is initialized with a brace-enclosed list of brace-enclosed lists. The enclosed braces are not syntactically required, but they lend clarity to the declaration. The following example program shows how a two-dimensional array is filled by such an initializer:
#include <iostream.h>
void main()
{
int rgI[2][4] = { 1, 2, 3, 4, 5, 6, 7, 8 };
for( int i = 0; i < 2; ++i )
for( int j = 0; j < 4; ++j )
cout << "rgI[" << i << "][" << j << "] = "
<< rgI[i][j] << endl;
}
The output from this program is:
rgI[0][0] = 1
rgI[0][1] = 2
rgI[0][2] = 3
rgI[0][3] = 4
rgI[1][0] = 5
rgI[1][1] = 6
rgI[1][2] = 7
rgI[1][3] = 8
Short initialization lists can be used only with explicit subaggregate initializers and enclosed in braces. If rgI
had been declared as:
int rgI[2][4] = { { 1, 2 }, { 3, 4 } };
the program output would have been:
rgI[0][0] = 1
rgI[0][1] = 2
rgI[0][2] = 0
rgI[0][3] = 0
rgI[1][0] = 3
rgI[1][1] = 4
rgI[1][2] = 0
rgI[1][3] = 0