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

8
  • It's not guaranteed to have equality. This has been discussed before on SO. Commented Apr 28, 2011 at 13:36
  • Where you expecting something different? Commented Apr 28, 2011 at 13:37
  • 1
    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. Commented Apr 28, 2011 at 13:38
  • 6
    The C Standard says (6.4.5/6): "It is unspecified whether [string literals] are distinct". Commented Apr 28, 2011 at 13:41
  • 1
    @pmg, that's what I was looking for. Make it an answer and I'll accept it. Commented Apr 28, 2011 at 13:42

3 Answers 3

12

The C Standard says (6.4.5/6)

It is unspecified whether [string literals] are distinct

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.