-1
if( "string1" == "string2" )    

Why does this work in C? It returns true when strings are equal? How? For example, it doesn't work in Java because the pointers are compared.

Blubberguy22
  • 1,344
  • 1
  • 17
  • 29
Gaureesh A
  • 11
  • 3

2 Answers2

3

The C99 Rationale says on string literals (emphasis mine):

"This specification allows implementations to share copies of strings with identical text, to place string literals in read-only memory, and to perform certain optimizations".

It is allowed but non-required so the result could be different with a different implementation or with the same implementation if the program is slightly different.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • 3
    Yes, but as you can see theses strings are different... I don't think this is the appropriate explanation. – Amessihel Jun 23 '15 at 15:33
  • @Amessihel I'm answering the point *"It returns true when strings are equal?"* when the string literals are different, the result is always `0`. – ouah Jun 23 '15 at 15:35
  • 3
    He says "why does this work?"... I understand *"why this returns true?"* but maybe It's not the case. – Amessihel Jun 23 '15 at 15:38
  • @Amessihel On *"Why does this work in C"* I guess he meant why is it valid and the answer is because the string literals are converted to pointer values and you can use pointer values as operands of `==` operator. Now when when the string literals are different as in his example, it is valid to use `==` but the result is always `0`. – ouah Jun 23 '15 at 15:38
  • He has to tell us exactly what he wants to know. – Amessihel Jun 23 '15 at 15:44
0

I think comparing string using 'if( "string1" == "string2" )' is comparing pointers to string literals in C. You could refer to the following post:- C String -- Using Equality Operator == for comparing two strings for equality

int main() {

    if( "string1" == "string1" ) {
        printf("Strings are equal\n");
    } else {
        printf("Strings are not equal\n");
    }

    if( "string1" == "string2" ) {
        printf("Strings are equal\n");
    } else {
        printf("Strings are not equal\n");
    }

    char* s1 = "string1";
    char* s2 = "string2";

    printf("%s = %p %s = %p\n", s1, s1, s2, s2);
    return(0);
}

There are two if blocks in the above main function. One of them if comparing "string1" with itself which will result in TRUE. The second is comparing "string1" and "string2" which will result in FALSE. If you assign pointers to the string literals and print their addresses you will be able to see why in the first if block you get TRUE value and in the second if block you get the FALSE value. Following is the output:-

GAGUPTA2-M-40UT:Desktop gagupta2$ ./a.out 
Strings are equal
Strings are not equal
string1 = 0x105f6ef50 string2 = 0x105f6ef82
Community
  • 1
  • 1
gaurav gupta
  • 147
  • 3