Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant strings address

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?
  ;
}
like image 936
big-z Avatar asked Oct 23 '09 06:10

big-z


People also ask

Where are constant strings stored?

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.

What is a constant string?

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.

How do you declare a string constant?

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.

What is string constant explain with example?

A string constant is a sequence of characters surrounded by double quotation marks such as "4 horses". Copyright 2018 Actian Corporation.


1 Answers

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.

like image 102
Michael Burr Avatar answered Sep 20 '22 15:09

Michael Burr