I'd like to ask if is it portable to rely on string literal address across translation units? I.e:
A given file foo.c has a reference to a string literal "I'm a literal!", is it correct and portable to rely that in other given file, bar.c in instance, that the same string literal "I'm a literal!" will have the same memory address? Considering that each file will be translated to a individual .o file.
For better illustration, follows an …
所以我做了以下测试:
char* a = "test";
char* b = "test";
char* c = "test\0";
Run Code Online (Sandbox Code Playgroud)
现在的问题是:
1)有保证a==b吗?我知道我在比较地址.这并不是要比较字符串,而是将相同的字符串文字存储在单个内存位置
2)为什么不a==c呢?编译器是否应该能够看到它们引用相同的字符串?
3)是否\0附加了额外的内容c,即使它已经包含一个?
我不想为此提出3个不同的问题,因为它们似乎有点相关,对不起'.
注意:标签是正确的,我对C++感兴趣.(虽然请指明C的行为是否不同)
以下比较是否保证是真的?
"hello world"=="hello world";
Run Code Online (Sandbox Code Playgroud)
此外,以下始终保证是假的吗?
char a[] = "hello world";
a == "hello world";
Run Code Online (Sandbox Code Playgroud)