• Advertisement
Sign in to follow this  

Silly Question On Static Arrays

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a quick question on static arrays. I'm trying to define a class member as a static array. I keep on getting compile errors. How would you initialize it? If it were " static int MyVar;", I would do "int MyClass::MyVar = 0;" before I start defining the rest of my class. What do I do when it's "static int MyVar[MAX_VARS]; " Thanks. I know it's stupid question that I should I already know the answer to. Oops. I'm using C++ if you can't tell.

Share this post


Link to post
Share on other sites
Advertisement
If you want to have a predefined array with all zeros, you could do
int MyClass::MyVar[MAX_VARS] = { 0 };
in your implementation file.

If you want to have a predefined array with different values, you could do
int MyClass::MyVar[MAX_VARS] = { 1,2,3,8,4,-5000 };
in your implementation file. I assume that the count of numbers must match MAX_VARS (maybe I'm wrong here, and there is some fallback mode that fills up missed values).

You could also allocate an array by static initializer if using
int* MyClass::MyVar = new int[MAX_VARS];
in your implementation file. This may be more appropriate if you need a large array and could initialize it lazily.

Share this post


Link to post
Share on other sites
Thanks. I always forget the bracket style way of defining arrays. I usually do a for loop and define via indexing.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement