Given the code
// somewhere in the program
const char* p1 = \"Hello World\";
// somewhere else in the program
const char* p2 = \"Hello World\";
There is no requirement that two string literals with the same text are the same object. So the two mentions of ”Hello world”
may or may not refer to a single string in memory. That means that
const char* p1 = "Hello World";
const char* p2 = "Hello World";
Does not necessarily make p1
equal to p2
. To do that, you have to set one of them equal to the other:
const char* p2 = p1;
But either one of those pointers can be modified, and the other pointer won’t track that change. To make sure that such changes can’t be done, make the pointers const:
const char* const p1 = "Hello World";
const char* const p2 = p1;
Or, if p1
needs to be modifiable, make p2
a reference:
const char* p1 = "Hello World";
const char*& p2 = p1;
Now p2
will point at whatever p1
points at.