用等号C字符串比较 [英] C Strings Comparison with Equal Sign
问题描述
我有这样的code:
的char * name =乔治如果(名称==乔治)
的printf(这是乔治)
我认为C字符串无法 ==
符号进行比较,我必须使用 STRCMP
。当我用gcc编译不明原因(4.7.3版本),这code工作。我虽然那是因为它是像这样我在谷歌搜索比较指针和很多人说这是错的,并与比较==
不能这样做,这是不对的。那么,为什么这种比较方法的工作?
我认为C字符串无法==符号进行比较,我必须使用STRCMP
块引用>右键
不过,我觉得这是错的,因为它是比较喜欢三分球,所以我在谷歌搜索,很多人说这是错误的,用==比较无法做到的。
块引用>这是正确的了。
那么,为什么这种比较方法有效?
块引用>它不工作。它只似乎是工作。的
为什么出现这种情况的原因可能是一个编译器的优化:这两个字符串是相同的,所以编译器确实产生只是其中的一个实例,并使用同样的指针/阵列每当字符串引用。
I have this code:
char *name = "George" if(name == "George") printf("It's George")
I thought that c strings could not be compared with
==
sign and I have to usestrcmp
. For unknown reason when I compile with gcc (version 4.7.3) this code works. 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 ?解决方案I thought that c strings could not be compared with == sign and I have to use strcmp
Right.
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
That's right too.
So why this comparing method works ?
It doesn't "work". It only appears to be working.
The reason why this happens is probably a compiler optimization: the two string literals are identical, so the compiler really generates only one instance of them, and uses that very same pointer/array whenever the string literal is referenced.
这篇关于用等号C字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!