<p>I'm quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time.</p>

<pre><code>int globalgarbage;
unsigned int anumber = 42;
</code></pre>

<p>But what about static ones defined within a function?</p>

<pre><code>void doSomething()
{
  static bool globalish = true;
  // ...
}
</code></pre>

<p>When is the space for <code>globalish</code> allocated? I'm guessing when the program starts. But does it get initialized then too? Or is it initialized when <code>doSomething()</code> is first called?</p>

[{'answer_id': 55515, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 2, 'selected': False, 'text': '<p>Static variables are allocated inside a code segment -- they are part of the executable image, and so are mapped in already initialized.</p>\n\n<p>Static variables within function scope are treated the same, the scoping is purely a language level construct.</p>\n\n<p>For this reason you are guaranteed that a static variable will be initialized to 0 (unless you specify something else) rather than an undefined value.</p>\n\n<p>There are some other facets to initialization you can take advantage off -- for example shared segments allow different instances of your executable running at once to access the same static variables.</p>\n\n<p>In C++ (globally scoped) static objects have their constructors called as part of the program start up, under the control of the C runtime library.  Under Visual C++ at least the order that objects are initialized in can be controlled by the <a href="http://support.microsoft.com/kb/104248" rel="nofollow noreferrer">init_seg</a> pragma.</p>\n'}, {'answer_id': 55548, 'author': 'Adam Pierce', 'author_id': 5324, 'author_profile': 'https://Stackoverflow.com/users/5324', 'pm_score': 8, 'selected': True, 'text': '<p>I was curious about this so I wrote the following test program and compiled it with g++ version 4.1.2.</p>\n\n<pre><code>include &lt;iostream&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\nclass test\n{\npublic:\n        test(const char *name)\n                : _name(name)\n        {\n                cout &lt;&lt; _name &lt;&lt; " created" &lt;&lt; endl;\n        }\n\n        ~test()\n        {\n                cout &lt;&lt; _name &lt;&lt; " destroyed" &lt;&lt; endl;\n        }\n\n        string _name;\n};\n\ntest t("global variable");\n\nvoid f()\n{\n        static test t("static variable");\n\n        test t2("Local variable");\n\n        cout &lt;&lt; "Function executed" &lt;&lt; endl;\n}\n\n\nint main()\n{\n        test t("local to main");\n\n        cout &lt;&lt; "Program start" &lt;&lt; endl;\n\n        f();\n\n        cout &lt;&lt; "Program end" &lt;&lt; endl;\n        return 0;\n}\n</code></pre>\n\n<p>The results were not what I expected. The constructor for the static object was not called until the first time the function was called. Here is the output:</p>\n\n<pre><code>global variable created\nlocal to main created\nProgram start\nstatic variable created\nLocal variable created\nFunction executed\nLocal variable destroyed\nProgram end\nlocal to main destroyed\nstatic variable destroyed\nglobal variable destroyed\n</code></pre>\n'}, {'answer_id': 55570, 'author': 'Eugene', 'author_id': 1155, 'author_profile': 'https://Stackoverflow.com/users/1155', 'pm_score': 5, 'selected': False, 'text': '<p>The memory for all static variables is allocated at program load. But local static variables are created and initialized the first time they are used, not at program start up. There\'s some good reading about that, and statics in general, <a href="https://web.archive.org/web/20100328062506/http://www.acm.org/crossroads/xrds2-4/ovp.html" rel="noreferrer">here</a>. In general I think some of these issues depend on the implementation, especially if you want to know where in memory this stuff will be located.</p>\n'}, {'answer_id': 55592, 'author': 'Henk', 'author_id': 4613, 'author_profile': 'https://Stackoverflow.com/users/4613', 'pm_score': 3, 'selected': False, 'text': '<p>The compiler will allocate static variable(s) defined in a function <code>foo</code> at program load, however the compiler will also add some additional instructions (machine code) to your function <code>foo</code> so that the first time it is invoked this additional code will initialize the static variable (e.g. invoking the constructor, if applicable).</p>\n\n<p>@Adam: This behind the scenes injection of code by the compiler is the reason for the result you saw.</p>\n'}, {'answer_id': 55877, 'author': 'dmityugov', 'author_id': 3232, 'author_profile': 'https://Stackoverflow.com/users/3232', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>Or is it initialized when doSomething() is first called?</p>\n</blockquote>\n\n<p>Yes, it is. This, among other things, lets you initialize globally-accessed data structures when it is appropriate, for example inside try/catch blocks. E.g. instead of</p>\n\n<pre><code>int foo = init(); // bad if init() throws something\n\nint main() {\n  try {\n    ...\n  }\n  catch(...){\n    ...\n  }\n}\n</code></pre>\n\n<p>you can write</p>\n\n<pre><code>int&amp; foo() {\n  static int myfoo = init();\n  return myfoo;\n}\n</code></pre>\n\n<p>and use it inside the try/catch block. On the first call, the variable will be initialized. Then, on the first and next calls, its value will be returned (by reference).</p>\n'}, {'answer_id': 58804, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': False, 'text': '<p>Some relevant verbiage from C++ Standard:</p>\n\n<blockquote>\n  <h2>3.6.2  Initialization of non-local objects          [basic.start.init]</h2>\n  \n  <h3>1</h3>\n  \n  <p>The   storage   for   objects    with    static    storage \n  duration   (<em>basic.stc.static</em>) shall be zero-initialized (<em>dcl.init</em>)\n  before any   other   initialization  takes  place. Objects  of \n  POD    types   (<em>basic.types</em>) with static storage duration\n  initialized with constant   expressions (<em>expr.const</em>) shall be \n  initialized  before  any  dynamic   initialization  takes  place. \n  Objects of namespace scope with static   storage duration defined in\n  the same translation unit and  dynamically   initialized  shall  be\n  initialized in the order in which their definition  appears  in \n  the  translation  unit. [Note:  <em>dcl.init.aggr</em>  describes  the \n  order in which aggregate members are initialized. The \n  initialization of local static objects is described in <em>stmt.dcl</em>.  ]</p>\n  \n  <p>[more text below adding more liberties for compiler writers]</p>\n  \n  <h2>6.7  Declaration statement                                  [stmt.dcl]</h2>\n  \n  <p>...</p>\n  \n  <h3>4</h3>\n  \n  <p>The zero-initialization (<em>dcl.init</em>) of all local objects with \n  static storage  duration  (<em>basic.stc.static</em>) is performed before\n  any other initialization  takes   place. A   local  object of \n  POD type (<em>basic.types</em>)  with static  storage  duration\n  initialized with constant-expressions is initialized before its\n  block is first entered. An implementation  is  permitted to perform\n  early initialization of other local objects with static storage\n  duration under the same conditions that an implementation is\n  permitted to statically initialize an object with static storage\n  duration in namespace scope  (<em>basic.start.init</em>). Otherwise  such\n  an object is initialized the first time control passes through its\n  declaration; such an object is considered initialized upon the\n  completion of its initialization. If the initialization exits by \n  throwing an exception, the initialization is not complete, so it will\n  be  tried again the next time control enters the declaration.  If control re-enters the declaration (recursively) while the object is being\n  initialized, the behavior is undefined.  [<em>Example:</em></p>\n\n<pre><code>      int foo(int i)\n      {\n          static int s = foo(2*i);  // recursive call - undefined\n          return i+1;\n      }\n</code></pre>\n  \n  <p>--<em>end example</em>]</p>\n  \n  <h3>5</h3>\n  \n  <p>The destructor for a local object with static storage duration will\n  be   executed  if  and  only  if  the  variable  was  constructed. \n  [Note:   <em>basic.start.term</em>  describes  the  order  in which local\n  objects with   static storage duration are destroyed.  ]</p>\n</blockquote>\n'}, {'answer_id': 20355603, 'author': 'Thang Le', 'author_id': 2103515, 'author_profile': 'https://Stackoverflow.com/users/2103515', 'pm_score': 3, 'selected': False, 'text': '<p>I try to test again code from <strong>Adam Pierce</strong> and added two more cases: static variable in class and POD type. My compiler is g++ 4.8.1, in Windows OS(MinGW-32).\nResult is static variable in class is treated same with global variable. Its constructor will be called before enter main function.</p>\n<ul>\n<li>Conclusion (for g++, Windows environment):</li>\n</ul>\n<ol>\n<li><strong>Global variable</strong> and <strong>static member in class</strong>: constructor is called before enter <strong>main</strong> function <em><strong>(1)</strong></em>.</li>\n<li><strong>Local static variable</strong>: constructor is only called when execution reaches its declaration at first time.</li>\n<li>If <strong>Local static variable is POD type</strong>, then it is also initialized before enter <strong>main</strong> function <em><strong>(1)</strong></em>.\nExample for POD type: <em>static int number = 10;</em></li>\n</ol>\n<p><strong>(1)</strong>: The correct state should be: <em>&quot;before any function from the same translation unit is called&quot;.</em> However, for simple, as in example below, then it is <em>main</em> function.</p>\n<pre><code>#include &lt;iostream&gt;                     \n#include &lt;string&gt;\n\nusing namespace std;\n\nclass test\n{\npublic:\n   test(const char *name)\n            : _name(name)\n    {\n            cout &lt;&lt; _name &lt;&lt; &quot; created&quot; &lt;&lt; endl;\n    }\n\n    ~test()\n    {\n            cout &lt;&lt; _name &lt;&lt; &quot; destroyed&quot; &lt;&lt; endl;\n    }\n\n    string _name;\n    static test t; // static member\n };\ntest test::t(&quot;static in class&quot;);\n\ntest t(&quot;global variable&quot;);\n\nvoid f()\n{\n    static  test t(&quot;static variable&quot;);\n    static int num = 10 ; // POD type, init before enter main function\n    \n    test t2(&quot;Local variable&quot;);\n    cout &lt;&lt; &quot;Function executed&quot; &lt;&lt; endl;\n}\n\nint main()\n{\n    test t(&quot;local to main&quot;);\n    cout &lt;&lt; &quot;Program start&quot; &lt;&lt; endl;\n    f();\n    cout &lt;&lt; &quot;Program end&quot; &lt;&lt; endl;\n    return 0;\n }\n</code></pre>\n<p><strong>result:</strong></p>\n<pre><code>static in class created\nglobal variable created\nlocal to main created\nProgram start\nstatic variable created\nLocal variable created\nFunction executed\nLocal variable destroyed\nProgram end\nlocal to main destroyed\nstatic variable destroyed\nglobal variable destroyed\nstatic in class destroyed\n</code></pre>\n<p>Anybody tested in Linux env ?</p>\n'}, {'answer_id': 70837256, 'author': 'Sherif Beshr', 'author_id': 15441343, 'author_profile': 'https://Stackoverflow.com/users/15441343', 'pm_score': -1, 'selected': False, 'text': '<p>In the following code it prints Initial = 4 which is the value of static_x as it is implemented in the compiling time.</p>\n<pre><code> int func(int x)\n    {\n        static int static_x = 4;\n        static_x = x;\n        printf (&quot;Address = 0x%x&quot;,&amp;static_x );   // prints 0x40a010\n        return static_x;\n    }\n    int main()\n    {\n        int x = 8;\n        uint32_t *ptr = (uint32_t *)(0x40a010); // static_x location\n        printf (&quot;Initial = %d\\n&quot;,*ptr);\n        func(x);\n    \n        return 0;\n    }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/55510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4790/']