devxlogo

Differences Between Initialization Forms

Differences Between Initialization Forms

Suppose you have an aggregate, i.e., a struct or a union that contain another struct as a member:

 struct A{ int x; int y;};union B{ A var1; float  var2;};

size=3>
Can you tell the difference between the following initialization forms?

 B arr[3] = {1,1,1}; B arr[3] = {{1},{1},{1}}; 

size=3>
The first statement initializes the three members of arr[0] to 1 whereas the remaining elements are zero initialized. In other words, it sets the values of arr[0] to:

 arr[0].var1.x =1; arr[0].var1.y=1;arr[0].var2=1;

size=3>
while the members of the elements arr[1] and arr[2] are zeroed.
By contrast, the second initialization statement contains explicit bracketing for each array element. It initializes only the first member of each element to 1, while leaving the rest of the members zero-initialized:

 arr[0].var1.x=1; arr[0].var1.y=0; arr[0].var2=0; arr[1].var1.x=1;//..rest of the members are zero-initializedarr[2].var1.x=1;//..rest of the members are zero-initialized

size=3>

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist