比较 C 中的文字空字符串
在 C 语言中,以下指定要做什么?
if ("" == "")
{
printf("Empty strings are equal\n");
}
我手头上有一个编译器,它告诉我 ""
确实等于 ""
。但这种平等能得到保证吗?
编辑:我完全理解指针比较和字符串比较在 C 中的工作原理。我要问的是,C 标准中为编译时常量空字符串指定了哪些行为(如果有)。我的信念是,字符串不能保证相等,但实际上通常是相等的,因为所有 const 空字符串都将被保留到同一地址。但我想知道是否有人可以提供明确的参考
In C, what is the following specified to do?
if ("" == "")
{
printf("Empty strings are equal\n");
}
I have a compiler on hand that tells me that ""
is indeed equal to ""
. But is this equality guaranteed?
Edit: I understand perfectly well how pointer comparison and string comparison work in C. What I'm asking is what behavior, if any, is specified in the C standard for compile-time constant empty strings. My belief is that the strings are not guaranteed to be equal, but in practice usually will be equal since all const empty strings will be interned to the same address. But I want to know if anyone can provide a definitive reference
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C 标准说(6.4.5/ 6)
The C Standard says (6.4.5/6)
有保证吗?我对此表示怀疑。您不是比较字符串的内容,而是比较它们的地址,这意味着您依赖编译器不会发出两个恰好在同一位置具有相同内容的文字字符串。它可能会起作用,但不是您应该依赖的东西(也不清楚它的用途是什么)。
编辑:另请参阅 为什么 C 中是“a”!=“a”? -它对基本相同的问题有一个答案,有近一百个赞成票(并且是由编译器以不同方式执行的用户编写的)。
Guaranteed? I doubt it. You're not comparing the content of the strings but rather their addresses, which means that you're relying on the compiler to not emit two literal strings that happen to have the same content in the same location. It's likely to work, but not something you should rely on (nor is it clear what it's useful for).
Edit: See also Why is "a" != "a" in C? - it has an answer to basically the same question with nearly a hundred upvotes (and was written by a user whose compiler did it differently).
我不认为有任何保证这些将具有相同的地址 - 我怀疑该标准是否需要这种行为。为什么你需要依赖它是可预测的?
I don't think there is any guarantee that these will have the same address -- I doubt the standard would require such behavior. Why would you need to depend on this being predictable?