what is aggregate initialization

First of all, to answer the main question, aggregate initialization means the use of brace-enclosed initializer lists to initialize all members of an aggregate (i.e. an array or struct [in C++, only certain types of structs count as aggregates]).

Obviously,

int ar[] = { 1 , 2 };

is safer than

int ar[2];
ar[0] = 1;
ar[1] = 2;

because the latter gives ample opportunity for typos and other errors in the indices of the individual elements to be initialized.

Looking at today’s C and C++, it’s unclear to me why the author makes a distinction between C and C++. Both languages enable aggregate initialization for arrays.

One possibility is that the author referred to old versions of the C Standard. Notably, in ANSI C (C89) an important restriction applied to the use of aggregate initialization: All initializers had to be constant expressions:

/* This is possible in C89: */
f(int i)
{ int ar[] = { 1 , 2 }; }

/* But this is not
   (because i is not a constant expression):
*/
f(int i)
{ int ar[] = { i , i+1 }; }

This is due to 3.5.7 in C89 (quoting from the draft I found here):

All the expressions in an initializer for an object that has static storage duration or in an initializer list for an object that has aggregate or union type shall be constant expressions.

This clearly limits the usefulness of aggregate initialization (and even in 1989, I believe many compilers implemented extensions to enable aggregate initialization also for non-constant expressions).

Later versions of the C Standard did not have this restriction, and the standardized versions of C++ (starting with C++98), I believe, never had any such restriction.

I can only speculate, but perhaps this is what the author had in mind?

Leave a Comment