title: C++ global variable initialization order
body: <p>I don't understand what the following code example does and how it does it:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int f();
  
  int a = f(); // a exists just to call f
  
  int x = 22;
  
  int f() {
      ++x;
      return 123; // unimportant arbitrary number
  }
  
  int main() {
      printf("%d\n", x);
  }
  </code></pre>
  
  <p>When this is ran it prints <code>23</code>, which is the intuitive answer.</p>
  
  <p>However in C++, global variables are <a href="https://stackoverflow.com/a/3746249/924313">supposed to be</a> initialized in order of definition. That would mean that <code>a</code> should be initialized before <code>x</code>, because it is defined before <code>x</code>. If that was the case, then the function <code>f</code> would have to be called before <code>x</code> was initialized, because the call to <code>f</code> is a part of <code>a</code>'s definition.</p>
  
  <p>If <code>f</code> is indeed called before <code>x</code> is initialized, that would mean that <code>f</code> would try to increment <code>x</code> -- the result of which I'm not really certain of (most likely UB, or some gibberish value). Then, after <code>a</code> is initialized, <code>x</code> would be initialized to <code>22</code> and the program would print out <code>22</code>.</p>
  
  <p><strong>Evidently that's not what happens. But what does? What does that code actually do?</strong></p>
  
  <p>It definitely seems like <code>x</code> is set to <code>22</code> before <code>a = f()</code> is evaluated, but that would mean that the order of initialization is reversed (I could also be wrong about what initialization is, or when it happens).</p>