Home > Blockchain >  Static local variables' initialization at program startup
Static local variables' initialization at program startup

Time:01-29

cppreference states:

Variables declared at block scope with the specifier static or thread_local (since C 11) have static or thread (since C 11) storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered).

My question is about that "unless" part - can you give examples of code where the static local variable is zero- and constant-initialized? Can class objects (e.g. MyClass obj;) be zero- or constant-initialized? If so, does that mean their constructor would be called before main() starts?

CodePudding user response:

can you give examples of code where the static local variable is zero- and constant-initialized?

In the below given example, the local static variable n satisfies both the conditions for constant initialization so that here the "unless" part in your quoted statement also holds.

int main()
{
     static const int i = 5; //both conditions for constant initialization are satisfied so that the "unless" part of your quoted statement also holds
}

A variable or temporary object obj is constant-initialized if

  • either it has an initializer or its default-initialization results in some initialization being performed, and

  • its initialization full-expression is a constant expression, except that if obj is an object, that full-expression may also invoke constexpr constructors for obj and its subobjects even if those objects are of non-literal class types (since C 11).


Can class objects (e.g. MyClass obj;) be zero- or constant-initialized?

Yes class objects can also be constant initialized.

struct Custom
{
    constexpr Custom()
    {
        
    }
};
int main()
{
     static constexpr Custom obj;//here also both conditions for constant initialization are satisfied
}

CodePudding user response:

According to this: https://en.cppreference.com/w/cpp/language/zero_initialization

Zero-initialization is performed [...] For every named variable with static [...] storage duration that is not subject to constant initialization, before any other initialization.

So in this context

int main() {
    ...
    static MyClass a;
    ...
}

zero-initialization of a can be performed before main() starts, but its constructor will be called inside of main() as expected.

  • Related