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