Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The section "Array Initialization" in Chapter 4, page 231 of "Thinking in Java, 2nd Edition" has this to say:

Initializing arrays in C is error-prone and tedious. C++ uses aggregate initialization to make it much safer. Java has no “aggregates” like C++, since everything is an object in Java. It does have arrays, and these are supported with array initialization.

Why is it error prone and tedious in C? What does it mean by aggregate initialization and why is it safer? I came across the chapter "Aggregate initialization" in Bruce Eckel's "Thinking in C++" (2nd Ed.), but it doesn't convince me of anything.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
184 views
Welcome To Ask or Share your Answers For Others

1 Answer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...