Home >Backend Development >C++ >Why Can't I Initialize Non-Constant Static Member Variables Within a C Class?
In C , attempting to define a public static variable with an initial value, such as static int j=0;, triggers a compilation error. This is attributed to the fundamental rule in ISO C that prohibits in-class initialization of non-constant static member variables.
Unlike in C, where such variables are implicitly initialized to zero, C mandates that they remain uninitialized. This distinction stems from the principle of referential transparency, which ensures that a static member's value remains consistent across all instances of the class. Allowing in-class initialization could compromise this principle, leading to inconsistencies in variable values.
In contrast to non-constant members, constant static members are permitted to be initialized in-class because their values cannot be modified after initialization. This means that these members maintain a consistent value throughout their lifetime.
The prohibition of in-class initialization implies that static variables in C are not automatically initialized with 0 as in C. Instead, they remain uninitialized until explicitly assigned a value elsewhere in the program.
To properly initialize static variables in C , it is necessary to define them in the header file and assign initial values in a separate .cpp file, as shown in the code snippet below:
// Header file class Test { public: static int j; }; // .cpp file // Initialize static variables int Test::j = 0;
By following this approach, you can ensure that static variables are initialized properly and consistently across all class instances.
The above is the detailed content of Why Can't I Initialize Non-Constant Static Member Variables Within a C Class?. For more information, please follow other related articles on the PHP Chinese website!