Initialization

Started by
4 comments, last by Plasmator 17 years, 11 months ago
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...
Advertisement
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.
------------------------------Support the Blue Skies in Games Campaign!A blog... of sorts.As a general rule, if you don't have a general rule in your signature, you aren't as awesome as someone who does. General rules roxor teh big one one ones.
Thanks :)
Quote:Original post by Plasmator
Hello 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.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...


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

- xeddiex
one..
Quote:Original post by programwizard
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.


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.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
Thanks a lot for your responses, Ratings!

This topic is closed to new replies.

Advertisement