I have several identical string constants in my program:
const char* Ok()
{
return "Ok";
}
int main()
{
const char* ok = "Ok";
}
Is there guarantee that they are have the same address, i.e. could I write the following code? I heard that GNU C++ optimize strings so they have the same address, could I use that feature in my programs?
int main()
{
const char* ok = "Ok";
if ( ok == Ok() ) // is it ok?
;
}
Best Solution
There's certainly no guarantee, but it is a common (I think) optimization.
The C++ standard says (2.13.4/2 "String literals):
To be clear, you shouldn't write code that assumes this optimization will take place - as Chris Lutz says, C++ code that relies on this is code that's waiting to be broken.