Home >Backend Development >C++ >How to Mimic Java Static Blocks in C : Initialization Strategies and Considerations
C Equivalents to Java Static Blocks
In Java, static blocks provide a convenient way to initialize static members before the class is instantiated. However, C does not have static blocks within classes.
Option 1: Initialization at Process Load
To achieve initialization at process load, use static variables outside of any class, also known as "translation unit scope."
<code class="cpp">// translation-unit-scope-static-initialization.cpp static_block { // Code to initialize your static variables }</code>
Option 2: Initialization at Class Instantiation
As C does not allow initialization of non-const static members, we need an indirect approach. Here's a workaround:
<code class="cpp">// static-initialized-via-base-class.cpp class StaticInitialized { public: static bool staticsInitialized = false; virtual void initializeStatics() = 0; }; class MyClass : private StaticInitialized { static int field1; static int field2; private: void initializeStatics() override { // Code to initialize field1 and field2 } };</code>
One caveat is that both options do not guarantee the order of initialization, as static variable initialization order in C is not deterministic.
The above is the detailed content of How to Mimic Java Static Blocks in C : Initialization Strategies and Considerations. For more information, please follow other related articles on the PHP Chinese website!