In C开发者_如何学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
The C Standard says (6.4.5/6)
It is unspecified whether [string literals] are distinct
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?
精彩评论