How to initialize an array

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
 
J

Jeroen Mostert

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.
 
P

PvdG42

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;
 
P

Pavel Minaev

   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] = {};
 
J

Jeroen Mostert

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};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top