title: How is static variable initialization implemented by the compiler?
body: <p>I'm curious about the underlying implementation of static variables within a function.</p>
  
  <p>If I declare a static variable of a fundamental type (char, int, double, etc.), and give it an initial value, I imagine that the compiler simply sets the value of that variable at the very beginning of the program before <code>main()</code> is called:</p>
  
  <pre><code>void SomeFunction();
  
  int main(int argCount, char ** argList)
  {
      // at this point, the memory reserved for 'answer'
      // already contains the value of 42
      SomeFunction();
  }
  
  void SomeFunction()
  {
      static int answer = 42;
  }
  </code></pre>
  
  <p>However, if the static variable is an instance of a class:</p>
  
  <pre><code>class MyClass
  {
      //...
  };
  
  void SomeFunction();
  
  int main(int argCount, char ** argList)
  {
      SomeFunction();
  }
  
  void SomeFunction()
  {
      static MyClass myVar;
  }
  </code></pre>
  
  <p>I know that it will not be initialized until the first time that the function is called. Since the compiler has no way of knowing when the function will be called for the first time, how does it produce this behavior? Does it essentially introduce an if-block into the function body?</p>
  
  <pre><code>static bool initialized = 0;
  if (!initialized)
  {
      // construct myVar
      initialized = 1;
  }
  </code></pre>