Why Can't Non-Const Static Members or Static Arrays Be Initialized within a Class?
Within a class, static data members can only be initialized if they are constant and of integral type. This restriction arises from the C standard's requirement that every object has a unique definition.
Non-Const Static Member Initialization:
According to the C standard (C 03 9.4.2), static data members of non-const types cannot be initialized within the class definition. The following code illustrates this:
class A { static int b = 3; };
This code violates the standard and will produce an error, as the static member b is non-const and attempts to initialize it within the class.
Static Array Initialization:
Similarly, static arrays cannot be initialized within a class definition, even if they are const. This is due to the fact that static arrays are stored in memory as objects. As such, they cannot be initialized within the class definition, as it would violate the requirement for unique definitions.
class A { static const int c[2] = { 1, 2 }; };
Once again, this code violates the standard and will produce errors.
Workaround and Reasons:
One workaround for initializing a static array within a class involves using the "enum trick," as follows:
class A { static const int a = 3; enum { arrsize = 2 }; static const int c[arrsize] = { 1, 2 }; };
The reason behind the prohibition on in-class initialization of static data members is related to the fact that header files containing class declarations are typically included into multiple translation units. To avoid linker issues, C requires that every object has a unique definition. If in-class initialization of memory-resident entities were allowed, this rule would be broken.
However, in C 11, the restriction has been relaxed to some extent. If a static data member is of a const literal type, it can be initialized using a brace-or-equal-initializer within the class definition. Additionally, non-static data members can now be initialized at the point of declaration. These features are not yet fully implemented in all compilers, such as gcc 4.7.
The above is the detailed content of Why Can't Non-Const Static Members or Static Arrays Be Initialized Inside a Class Definition in C ?. For more information, please follow other related articles on the PHP Chinese website!