比较 C 中的文字空字符串

发布于 2024-11-03 17:34:54 字数 353 浏览 0 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小矜持 2024-11-10 17:34:54

C 标准说(6.4.5/ 6)

未指定[字符串文字]是否不同

The C Standard says (6.4.5/6)

It is unspecified whether [string literals] are distinct

初熏 2024-11-10 17:34:54

有保证吗?我对此表示怀疑。您不是比较字符串的内容,而是比较它们的地址,这意味着您依赖编译器不会发出两个恰好在同一位置具有相同内容的文字字符串。它可能会起作用,但不是您应该依赖的东西(也不清楚它的用途是什么)。

编辑:另请参阅 为什么 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).

橘寄 2024-11-10 17:34:54

我不认为有任何保证这些将具有相同的地址 - 我怀疑该标准是否需要这种行为。为什么你需要依赖它是可预测的?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文