title: How long does a string constant live in c++?
body: <p>I've been wondering, how long does a string constant live in C++. For example, if I create some const char *str = "something" inside a function, would it be safe to return the value of str?</p>
  
  <p>I wrote a sample program and was really surprised to see that such returned value still stored that string. Here is the code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  const char *func1()
  {
      const char *c = "I am a string too";
      return c;
  }
  
  void func2(const char *c = "I'm a default string")
  {
      cout &lt;&lt; c &lt;&lt; endl;
  }
  
  const int *func3()
  {
      const int &amp;b = 10;
      return &amp;b;
  }
  
  int main()
  {
      const char *c = "I'm a string";
      cout &lt;&lt; c &lt;&lt; endl;
      cout &lt;&lt; func1() &lt;&lt; endl;
      func2();
      func2("I'm not a default string");
      cout &lt;&lt; *func3() &lt;&lt; endl;
      return 0;
  }
  </code></pre>
  
  <p>It gives me the following output:</p>
  
  <blockquote>
    <p>I'm a string</p>
    
    <p>I am a string too</p>
    
    <p>I'm a default string</p>
    
    <p>I'm not a default string</p>
    
    <p>10</p>
  </blockquote>
  
  <p>The func3 is there just to find out if the same works with other types.<br>
  So the question is: is it safe to return a pointer to a string constant created within that function (as in func1())?<br>
  Also, is it safe to use the default string value as in func2()?</p>