Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing Constant Static Array In Header File

I have just found out that the following is not valid.

//Header File class test {     const static char array[] = { '1', '2', '3' }; }; 

Where is the best place to initialize this?

like image 383
user174084 Avatar asked Jan 22 '10 13:01

user174084


People also ask

Can you initialize an array in a header file?

You can't do it; the size of the array needs to be specified in the class declaration. If you want something variable-sized, use a vector. If you require dynamically sized arrays you should read into dynamic memory allocation with C++.

Are static arrays initialized to zero?

The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list. Designated Initializer: This initializer is used when we want to initialize a range with the same value. This is used only with GCC compilers.

Which array that are declared static are initialised?

Statically declared arrays are allocated memory at compile time and their size is fixed, i.e., cannot be changed later. They can be initialized in a manner similar to Java. For example two int arrays are declared, one initialized, one not. Static multi-dimensional arrays are declared with multiple dimensions.


2 Answers

The best place would be in a source file

// Header file class test {     const static char array[]; };  // Source file const char test::array[] = {'1','2','3'}; 

You can initialize integer types in the class declaration like you tried to do; all other types have to be initialized outside the class declaration, and only once.

like image 137
Mike Seymour Avatar answered Oct 01 '22 20:10

Mike Seymour


You can always do the following:

class test {   static const char array(int index) {     static const char a[] = {'1','2','3'};     return a[index];   }  }; 

A couple nice things about this paradigm:

  • No need for a cpp file
  • You can do range checking if you want to
  • You avoid having to worry about the static initialization fiasco
like image 27
JKD Avatar answered Oct 01 '22 20:10

JKD