Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
Jul 2, 2001

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-initialized
arr[2].var1.x=1;
//..rest of the members are zero-initialized
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date