我有这个代码:
char *name = "George"
if(name == "George")
printf("It's George")
我认为 c 字符串不能与 ==
符号进行比较,我必须使用 strcmp
。由于未知原因,当我使用 gcc(版本 4.7.3)编译时,此代码有效。我认为这是错误的,因为它就像比较指针,所以我在谷歌中搜索,很多人说这是错误的,无法与 ==
进行比较。那么为什么这种比较方法有效呢?
最佳答案
I thought that c strings could not be compared with == sign and I have to use strcmp
没错。
I though that this was wrong because it is like comparing pointers so I searched in google and many people say that it's wrong and comparing with == can't be done
也对。
So why this comparing method works ?
它不“工作”。它只是似乎在工作。
发生这种情况的原因可能是编译器优化:两个字符串文字是相同的,因此编译器实际上只生成它们的一个实例,并在引用字符串文字时使用完全相同的指针/数组。
关于C 字符串与等号的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17781855/