Sign in to follow this  
vladic2000x

Initializing a static class member array at definition?

Recommended Posts

Hi there! //file.h class foe { //I declare a static array of 1000 integers static int sArray[1000]; }; //file.cpp //how do I reset all of the array elements to 0, at definition? int foe::sArray[1000]; //....

Share this post


Link to post
Share on other sites
static variables are initialized to zero automatically.

If you wanted to initialize it to another value, I'm not sure there's a language supported way, but you could do something like this:


foe::foe() {
// inited is a static bool
if (!inited) {
// Initialize array elements
inited = true;
}
}

Share this post


Link to post
Share on other sites
Static member arrays can be initialized with an aggregate initializer list. Ex:

struct A {
static int array[100];
};

int A::array[100] = {
1, 2, 3
};

Share this post


Link to post
Share on other sites
Gage64,

I was actually using your solution, but because the program creates and destroys hundreds of objects dynamically I wanted to optimize the code as much as possible (there is an "if" call in the constructor).

Well, did a test to see if the static members are automatically initialized... and indeed they are.

SiCrane, your solution is good for a small array, but how about 10000 elements.


Share this post


Link to post
Share on other sites
you can have like a initArrays function that you call at the very starts. And you can clear all of your static arrays in it by using memset or zeromemory.

void initArrays ()
{
memset(arrayA, 0, byteSize);
)

Share this post


Link to post
Share on other sites
Quote:
Original post by vladic2000x
SiCrane, your solution is good for a small array, but how about 10000 elements.


Why would you want to initialize a large, static array in the code? Large amounts of "configuration" data should be read from a file instead, so that you (a) don't have to format it all with commas and braces, and (b) don't have to recompile just to change the data.

nhatkthanh: Don't use memset in C++; use std::fill.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this