title: Static Variable Pointer?
body: <p>Is this illegal/dangerous?</p>
  
  <pre><code>int* static_nonew()
  {
      static int n = 5;
      return &amp;n;
  }
  </code></pre>
  
  <p>The compiler doesn't seem to have a problem with it, but is the pointer location itself protected from being overwritten when someone else needs memory?</p>
  
  <p>EDIT: A little bit more of an explanation of why I asked this question. Note: I'm programming in C++, I just tagged it as C because it seemed to be more of a C than C++ question.</p>
  
  <p>I have a class that's supposed to return a static map. I only want this map initialized once throughout the program as there doesn't seem to be a need to do it multiple times. For this reason, I was going to have something like this:</p>
  
  <pre><code>static std::map&lt;std::string, Transition*&gt; transitions;
  static Transition trans1(transitions, ...);
  static Transition trans2(transitions, ...);
  return &amp;transitions;
  </code></pre>
  
  <p>The Transition classes constructor would add itself to the transitions. In that way, it would create the transitions once and then return a pointer to them. I just remember that if you create a reference to a variable allocated on the stack, it could get overwritten very easily and was "unsafe". I was just a bit confused with exactly how static variables created within a function work.</p>