Public Group

# Initialization

This topic is 4419 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello everyone, I've got a question... Look at this code,
struct BLA
{
int a;
double b;
char c;
};

//in main
BLA bla = {0};


From what I understand this will initialize the first variable to 0 (int a), but it seems that this is also true for b, and c! Also I've noticed that this works for arrays, like, char bla[256] = {0}; is this a valid way of setting an objects member variables, or is it just my compiler that's nulling everythiing because I'm in running in debug mode? Thanks in advance! P.S Also, if this is indeed a valid method of setting values to all of an objects members, is there any way to do this when you're using dynamic allocation? (malloc / new)? Thanks again...

##### Share on other sites
From what I can tell, all other veriables must be specifically set, otherwise they will all be filled with the value you specify first. bla={0} would make them all 0, but bla={0, 1, 2} would set a equal to 0, b equal to 1, and c equal to 2.

Thanks :)

##### Share on other sites
Quote:
 Original post by PlasmatorHello everyone, I've got a question...From what I understand this will initialize the first variable to 0 (int a), but it seems that this is also true for b, and c! Also I've noticed that this works for arrays, like, char bla[256] = {0}; is this a valid way of setting an objects member variables, or is it just my compiler that's nulling everythiing because I'm in running in debug mode?

Is your code in C? If yes, you should be doing struct Bla bla; instead.

What you are intializing is an aggregated structure. Initializing just one member of this structure, or an array (e.g.: array = {0}), will initialize the rest aswell.

Quote:
 P.SAlso, if this is indeed a valid method of setting values to all of an objects members, is there any way to do this when you're using dynamic allocation? (malloc / new)?Thanks again...

I don't think so unless, you, for example use a function such as calloc (in C).

- xeddiex

##### Share on other sites
Quote:
 Original post by programwizardFrom what I can tell, all other veriables must be specifically set, otherwise they will all be filled with the value you specify first. bla={0} would make them all 0, but bla={0, 1, 2} would set a equal to 0, b equal to 1, and c equal to 2.

Not quite. When you initialize a struct or class or array like that, the members not explicitly initialized are set to 0. For example, in this code
BLA bla = { 2 };
bla.a is 2 and bla.b and bla.c are 0.

##### Share on other sites
Thanks a lot for your responses, Ratings!

• 10
• 17
• 9
• 14
• 41