The C standard restricts the initialization of static data members within class definitions to only static constant integral or enumeration types.
class A { static const int a = 3; // Allowed static int b = 3; // Error: Non-const static member cannot be initialized in class definition static const int c[2] = {1, 2}; // Allowed static int d[2] = {1, 2}; // Error: Non-const static array cannot be initialized in class definition };
This limitation is due to the way static data members are handled by the compiler. Every static data member must have a unique definition, and if initialized in the class definition, it would create multiple definitions when the class is included in multiple translation units.
Static arrays, even constant arrays, cannot be initialized in class definitions because their size cannot be determined at compile time. The compiler requires the size of an array to be known before it can allocate memory for the array.
To initialize static arrays in class definitions, a workaround using the "enum trick" can be employed:
class A { static const int a = 3; enum { arrSize = 2 }; static const int c[arrSize] = {1, 2}; };
The standard's restriction on initializing non-const static members stems from the need to prevent ambiguous definitions and to ensure unique member definitions across translation units.
As for static arrays, the C language design has prioritized compile-time efficiency, requiring the array size to be known at compile time to optimize memory allocation. However, C 11 introduced the concept of constant expressions, allowing the initialization of const data members with values determined at compile time, which may provide more flexibility in future C versions.
The above is the detailed content of Why Can't Non-Const Static Members and Arrays Be Initialized Within a C Class Definition?. For more information, please follow other related articles on the PHP Chinese website!