Originally Posted by
Noir
Yes, a string constant has static lifetime.
The constant itself does, but it's still possible to shoot yourself in the foot. For instance:
Code:
#include <iostream>
// This function works correctly.
const char *get_string()
{
char *hello = "Hello!";
return hello;
}
// This function is wrong.
const char *get_string_2()
{
// But I'm still using a string constant, right? What's goin' on?
char hello[] = "Hello!";
return hello;
}
// This function makes sure you see the problem
void kill_stack(int a, int b, int c, int d, int e, int f, int g)
{
}
int main()
{
const char *str;
str = get_string();
std::cout << str << std::endl;
str = get_string_2();
kill_stack(1,2,3,4,5,6,7);
std::cout << str << std::endl;
return 0;
}
I'll leave it a mystery for those who don't get it. Arrays and pointers are not the same thing!