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?
;
}
Strings are stored on the heap area in a separate memory location known as String Constant pool. String constant pool: It is a separate block of memory where all the String variables are held. String str1 = "Hello"; directly, then JVM creates a String object with the given value in a String constant pool.
A string constant is an arbitrary sequence of characters that are enclosed in single quotation marks (' '). For example, 'This is a string'. You can embed single quotation marks in strings by typing two adjacent single quotation marks.
C string constants can be declared using either pointer syntax or array syntax: // Option 1: using pointer syntax. const char *ptr = "Lorem ipsum"; // Option 2: using array syntax.
A string constant is a sequence of characters surrounded by double quotation marks such as "4 horses". Copyright 2018 Actian Corporation.
There's certainly no guarantee, but it is a common (I think) optimization.
The C++ standard says (2.13.4/2 "String literals):
Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With