Home >Backend Development >C++ >Why Can't I Initialize Static Members and Arrays Directly in a C Class?
In C , static data members in a class cannot be initialized directly within the class definition, except for certain specific cases.
Static data members are allocated in the memory segment of the program and are shared among all instances of the class. The C standard forbids their in-class initialization to prevent multiple definitions of the same variable in multiple translation units.
Similarly, static arrays in a class cannot be initialized in-class because arrays occupy a contiguous block of memory. Allowing in-class initialization would lead to multiple copies of the same array being created in each translation unit, resulting in unexpected behavior.
An exception to these rules is made for static const integral types and enumeration types. These types can be initialized in-class because they are treated as compile-time constants and their values are known at the moment of compilation.
To initialize a static array in a class, you can use the "enum trick":
enum { arrsize = 2 };
static const int c[arrsize] = { 1, 2 };
This approach declares an enumeration constant arrsize to determine the array size, which is then used to initialize the static const array c.
C 11 has relaxed these restrictions somewhat. Now, static data members of certain types, known as "literal types," can be initialized in-class using a brace-or-equal-initializer. Additionally, C 11 allows non-static data members to be initialized in-class using constant expressions.
The above is the detailed content of Why Can't I Initialize Static Members and Arrays Directly in a C Class?. For more information, please follow other related articles on the PHP Chinese website!