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;};


Can you tell the difference between the following initialization forms?

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


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;


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

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: