title: C++ pointer to objects which go out of scope when function returns - why does this work?
body: <p>Both these calls to get_string and get_string2 return objects which go out of scope when the function returns.  Shouldn't the returned object be an address in memory which goes out of scope after the function returns? This is using Visual Studio 2008.  Should this always work?  Why?</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  enum myID { SMALL, MEDIUM, LARGE };
  
  const char* get_string(myID id) {
     switch(id){
        case SMALL: return "small";
        case MEDIUM: return "medium";
        case LARGE: return "large";
        default: return "unknown";
     }
  }
  
  const char* get_string2(myID id) {
     char* s = 0;
     switch(id){
        case SMALL:  s = "small"; return s;
        case MEDIUM: s = "medium"; return s;
        case LARGE:  s = "large"; return s;
        default: return "unknown";
     }
  }
  
  int main() {
     std::cout &lt;&lt; get_string(SMALL) &lt;&lt; std::endl;
     std::cout &lt;&lt; get_string2(SMALL) &lt;&lt; std::endl;
     return 0;
  }
  </code></pre>