How to initialize an array

  • Thread starter Thread starter Bob Altman
  • Start date Start date
B

Bob Altman

Hi all,

Here's a really basic C++ syntax question: How do I initialize an array,
whose size is a literal, to all zeros in its initializer without coding a
loop to do it? For example:

#define N 5
bool myData[N];

// Don't want to do this:
if (!m_initDone) {
for (int i = 0; i < N; i++) myData = false;
m_initDone = true;
}

TIA - Bob
 
Bob said:
Here's a really basic C++ syntax question: How do I initialize an array,
whose size is a literal, to all zeros in its initializer without coding a
loop to do it? For example:

#define N 5
bool myData[N];
bool myData[N] = {0};

Initialize part, initialize the whole. Works for structs, too.
 
Bob Altman said:
bool myData[N] = {0};

Initialize part, initialize the whole. Works for structs, too.

Thanks Jeroen.
You may well already be aware of this, but while the initialization
statement above does set all elements to 0, a statement such as bool
myData[N] = {1}; sets only the first element to 1, and the rest to 0. IOW, a
single initialization value occupies the first element and the compiler
initializes elements for which no explicit value was provided to 0;
 
   bool myData[N] = {0};

Initialize part, initialize the whole. Works for structs, too.

Actually, there's no need to explicitly initialize any part of it,
even; you can just do:

bool myData[N] = {};
 
PvdG42 said:
Bob Altman said:
bool myData[N] = {0};

Initialize part, initialize the whole. Works for structs, too.

Thanks Jeroen.
You may well already be aware of this, but while the initialization
statement above does set all elements to 0, a statement such as bool
myData[N] = {1}; sets only the first element to 1, and the rest to 0.
IOW, a single initialization value occupies the first element and the
compiler initializes elements for which no explicit value was provided
to 0;

Good point, I should have mentioned that. In fact, when using it to
initialize structs whose first member holds the size of the struct, you use
this explicitly:

Struct struct = {sizeof struct};
 
Back
Top