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?
I wrote a sample program and was really surprised to see that such returned value still stored that string. Here is the code:
#include <iostream>
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 << c << endl;
}
const int *func3()
{
const int &b = 10;
return &b;
}
int main()
{
const char *c = "I'm a string";
cout << c << endl;
cout << func1() << endl;
func2();
func2("I'm not a default string");
cout << *func3() << endl;
return 0;
}
It gives me the following output:
I'm a string
I am a string too
I'm a default string
I'm not a default string
10
The func3 is there just to find out if the same works with other types.
So the question is: is it safe to return a pointer to a string constant created within that function (as in func1())?
Also, is it safe to use the default string value as in func2()?