Possible Duplicate:
Is a string literal in c++ created in static memory?
If I do:
const char* StringPtr = "string0",
then it is definitely somewhere in the memory, and I can get the address of StringPtr.
But if I do:
#define STRING0 "string0", then where does STRING0 reside?
Or, is STRING0 not existing in memory because compiler replace using of STRING0 by "string0"?
As far as I’ve known, whenever you write any string in your code, compiler must put it somewhere in the memory, but I don’t know the exact behavior of it.
But I am not very sure about this.
Can anyone explain how strings that are #define-ed or declared as char* are manipulated by the compiler?
Also, which one is better? To #define, extern const char* or extern const std::stringin the header file for strings?
Thanks!
In almost all cases, the compiler is allowed to put a string literal wherever it wants. There might be one copy for each time the literal appears in source code, or one master copy shared among the instances.
This causes trouble sometimes in C where
constdoesn’t mean the same thing and you are allowed to modify the memory. On one platform all the identical strings get changed, while on another changes don’t propagate. As of C++11 string literals don’t implicitly loseconstness and the mistake is harder to make.The strings will all be initialized before the program starts, so in effect they are part of the executable binary image. That much is certain.
What would be different is this:
This defines a dedicated array object with a unique address.