4

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

JSBձոգչ
  • 40,684
  • 18
  • 101
  • 169

3 Answers3

12

The C Standard says (6.4.5/6)

It is unspecified whether [string literals] are distinct

pmg
  • 106,608
  • 13
  • 126
  • 198
5

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).

Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • John Zwinck is right, you're betting on the compiler's behavior. You should be using strcmp instead - unless, of course, you're REALLY interested in comparing addresses. – SolarBear Apr 28 '11 at 13:39
0

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?

Glen
  • 315
  • 2
  • 10