c++ - what is aggregate initialization -


the section array initialization in chapter 4, page 231 of thinking in java, 2nd edition has say:

initializing arrays in c error-prone , tedious. c++ uses aggregate initialization make safer. java has no “aggregates” c++, since object in java. have arrays, , these supported array initialization.

why error prone , tedious in c? mean aggregate initialization , why safer? came across this doesn't convince me of anything.

first of all, answer main question, aggregate initialization means use of brace-enclosed initializer lists initialize members of aggregate (i.e. array or struct [in c++, types of structs count aggregates]).

obviously,

int ar[] = { 1 , 2 }; 

is safer than

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

because latter gives ample opportunity typos , other errors in indices of individual elements initialized.

looking @ today's c , c++, it's unclear me why author makes distinction between c , c++. both languages enable aggregate initialization arrays.

one possibility author referred old versions of c standard. notably, in ansi c (c89) important restriction applied use of aggregate initialization: initializers had constant expressions:

/* possible in c89: */ f(int i) { int ar[] = { 1 , 2 }; }  /* not    (because not constant expression): */ f(int i) { int ar[] = { , i+1 }; } 

this due 3.5.7 in c89 (quoting draft found here):

all expressions in initializer object has static storage duration or in initializer list object has aggregate or union type shall constant expressions.

this limits usefulness of aggregate initialization (and in 1989, believe many compilers implemented extensions enable aggregate initialization non-constant expressions).

later versions of c standard did not have restriction, , standardized versions of c++ (starting c++98), believe, never had such restriction.

i can speculate, perhaps author had in mind?


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -