Home >Backend Development >C++ >How to Mimic Java Static Blocks in C : Initialization Strategies and Considerations

How to Mimic Java Static Blocks in C : Initialization Strategies and Considerations

Susan Sarandon
Susan SarandonOriginal
2024-10-27 09:16:03983browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn