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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With