Have a look at this code:

#include <iostream>
using namespace std;

int main()
{
    const char* str0 = "Watchmen";
    const char* str1 = "Watchmen";
    char* str2 = "Watchmen";
    char* str3 = "Watchmen";

    cerr << static_cast<void*>( const_cast<char*>( str0 ) ) << endl;
    cerr << static_cast<void*>( const_cast<char*>( str1 ) ) << endl;
    cerr << static_cast<void*>( str2 ) << endl;
    cerr << static_cast<void*>( str3 ) << endl;

    return 0;
}

Which produces an output like this:

0x443000
0x443000
0x443000
0x443000

This was on the g++ compiler running under Cygwin. The pointers all point to the same location even with no optimization turned on (-O0).

Does the compiler always optimize so much that it searches all the string constants to see if they are equal? Can this behaviour be relied on?

Edit
Report