void main() {
if("a" == "a")
printf("Yes, equal");
else
printf("No, not equal");
}
Run Code Online (Sandbox Code Playgroud)
为什么输出No, not equal?
刚刚在gdb中检查以下内容:
char *a[] = {"one","two","three","four"};
char *b[] = {"one","two","three","four"};
char *c[] = {"two","three","four","five"};
char *d[] = {"one","three","four","six"};
Run Code Online (Sandbox Code Playgroud)
我得到以下内容:
(gdb) p a
$17 = {0x80961a4 "one", 0x80961a8 "two", 0x80961ac "three", 0x80961b2 "four"}
(gdb) p b
$18 = {0x80961a4 "one", 0x80961a8 "two", 0x80961ac "three", 0x80961b2 "four"}
(gdb) p c
$19 = {0x80961a8 "two", 0x80961ac "three", 0x80961b2 "four", 0x80961b7 "five"}
(gdb) p d
$20 = {0x80961a4 "one", 0x80961ac "three", 0x80961b2 "four", 0x80961bc "six"}
Run Code Online (Sandbox Code Playgroud)
我真的很惊讶字符串指针对于相同的单词是相同的.我原以为每个字符串都会在堆栈上分配自己的内存,无论它是否与另一个数组中的字符串相同.
这是某种编译器优化的示例,还是这种字符串声明的标准行为?
看看这段代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
这会产生如下输出:
0x443000
0x443000
0x443000
0x443000
Run Code Online (Sandbox Code Playgroud)
这是在Cygwin下运行的g ++编译器.即使没有打开优化(),指针也指向相同的位置.-O0
编译器是否总是进行优化以至于它会搜索所有字符串常量以查看它们是否相等?可以依赖这种行为吗?