Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing literal empty strings in C

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

like image 700
JSBձոգչ Avatar asked Dec 04 '22 08:12

JSBձոգչ


2 Answers

The C Standard says (6.4.5/6)

It is unspecified whether [string literals] are distinct

like image 89
pmg Avatar answered Dec 21 '22 09:12

pmg


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

like image 33
John Zwinck Avatar answered Dec 21 '22 10:12

John Zwinck