Why do (only) some compilers use the same address for identical string literals?

后端 未结 4 2224
北恋
北恋 2020-12-13 01:07

https://godbolt.org/z/cyBiWY

I can see two \'some\' literals in assembler code generated by MSVC, but only one with clang and gcc. This leads to totally

4条回答
  •  温柔的废话
    2020-12-13 01:46

    The other answers explained why you cannot expect the pointer addresses to be different. Yet you can easily rewrite this in a way that guarantees that A and B don't compare equal:

    static const char A[] = "same";
    static const char B[] = "same";// but different
    
    void f() {
        if (A == B) {
            throw "Hello, string merging!";
        }
    }
    

    The difference being that A and B are now arrays of characters. This means that they aren't pointers and their addresses have to be distinct just like those of two integer variables would have to be. C++ confuses this because it makes pointers and arrays seem interchangeable (operator* and operator[] seem to behave the same), but they are really different. E.g. something like const char *A = "foo"; A++; is perfectly legal, but const char A[] = "bar"; A++; isn't.

    One way to think about the difference is that char A[] = "..." says "give me a block of memory and fill it with the characters ... followed by \0", whereas char *A= "..." says "give me an address at which I can find the characters ... followed by \0".

提交回复
热议问题