Home >Backend Development >C++ >How to Implement Static Code Blocks in C Without Using Classes?
While C does not directly support static code blocks within classes, a workaround is to utilize static code blocks outside classes. This approach allows for the execution of code during class loading or when the containing DLL is loaded.
To accomplish this, you can create a static block at translation unit scope, typically in the implementation file for your class. For example:
<code class="cpp">static_block { // Here you can perform initialization code std::cout << "Hello static block world!\n"; }</code>
By using static_block as shown above, the enclosed code will run before the main() function.
For this option, consider the following class structure:
<code class="cpp">class StaticInitialized { public: static bool staticsInitialized = false; virtual void initializeStatics(); StaticInitialized() { if (!staticsInitialized) { initializeStatics(); staticsInitialized = true; } } }; class MyClass : private StaticInitialized { public: static int field1; static int field2; protected: void initializeStatics() { // Here you can perform initialization code specific to MyClass field1 = 42; field2 = 100; } };</code>
In this example, the initializeStatics() function is virtual and can be overridden in derived classes for specific initialization logic. The StaticsInitialized flag ensures that the initialization code is only run once before any instance of the class is created.
The above is the detailed content of How to Implement Static Code Blocks in C Without Using Classes?. For more information, please follow other related articles on the PHP Chinese website!