How does MSVC optimize static variable usage?

Viewed 2198

I'm interested in how the Microsoft Visual C++ compiler treat/optimize static variables.

My code:

#include <cstdlib>

void no_static_initialization()
{
    static int value = 3;
}

void static_initialization(int new_value)
{
    static int value = new_value;
}

int main()
{
    no_static_initialization();
    static_initialization(1);
    static_initialization(std::rand());

    return 0;
}

Here's the assembly for the code (compiled with optimizations):

picture of the assembly listing

My main area of interest is the last case.

Here, the first statement got fully optimized and two calls of the second statement were inlined and they actually represent similiar chunks of code.

Each of them does test something something and then makes a short jump if the test wasn't successful (these jumps obviously point to the end of corresponding routine).

Does the compiler make an explicit check on every function call for if the function is called the first time?
Does the compiler actually have a flag, which indicates if this is the first time the function was called or not?
Where is it stored (I guess all that test stuff is about it, but I'm not exactly sure)?

2 Answers
Related