Is the initialization of global variable the same as the initialization of static variable inside a function

Viewed 68

I'm trying to figure out all different kinds of initialization in C++. Now I'm reading this link: https://en.cppreference.com/w/cpp/language/zero_initialization

In the example of this link, we have such a piece of code:

std::string s; // zero-initialized to indeterminate value
               // then default-initialized to ""

As my understanding, the initialization of the global variable is as below:

When we compile the code, the s is zero-initialized, it is put at the .bss segment of the binary file. When we run the binary file (meaning that the kernel is starting to load the binary file into RAM), the s is default-initialized to the empty string "".

Now, we define a function as below:

void func()
{
    static std::string s;
}

If we call the function first time, the s will be initialized, this is for sure. But is it still initialized with two methods: first zero initialization, then default initialization, just like the first s?

BTW, I'm working on Ubuntu, X86_64 architecture with the compiler GCC 7.5. If my question is not standardized by C++, you could tell me in the comment and I'll close this question.

1 Answers

But is it still initialized with two methods: first zero initialization, then default initialization, just like the first s?

Assuming, the "as-if"-rule effectively forces the compiler to consider the existence of this variable, yes. Excerpts from the standard:

Zero initialization is performed in the following situations:

  1. For every named variable with static or thread-local storage duration that is not subject to constant initialization, before any other initialization.

Default initialization is performed in three situations:

  1. when a variable with automatic, static, or thread-local storage duration is declared with no initializer;

As molbdnilo said within the comments, you should avoid thinking in terms of binary files, kernel and segments here totally if you are only interested in the behavior the standard claims.

Related