TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

 Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
Jul 3, 2001

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

# 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

 Submit a Tip Browse "C++" Tips Browse All Tips
Comment and Contribute

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

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