Search code examples
cstringstring-comparisonimplicit-conversionstring-literals

Does the C equality operator compare the literal value of two strings or their memory locations?


I cannot understand this behaviour of the == operator:

char s1[4];
s1[0] = 'a';
s1[1] = 'a';
s1[2] = 'a';
s1[3] = '\0';

char *s2 = "aaa";
char *s3 = "aaa";

printf("s1: %s\n", s1); // aaa
printf("s2: %s\n", s2); // aaa
printf("s3: %s\n", s3); // aaa
printf("s1 == s2: %d\n", (s1 == s2)); // 0
printf("s1 == s3: %d\n", (s1 == s3)); // 0
printf("s2 == s3: %d\n", (s2 == s3)); // 1

The literal value of all 3 strings is the same (aaa), so why is the comparison successful only between s2 and s3 and not between s1 and s2? Clearly they all have different memory locations so that cannot account for the result.

Thanks


Solution

  • This will compare the value of the pointers. in other words, the memory locations.

    The proper way to compare strings is using the library function strcmp:

      if(strcmp(s1, s2) == 0) { printf("The strings are the same."); }
    

    One of the risks with your code is that you have set the pointers equal to a static string. Even though you have written these as two separate strings, the compiler could easily optimize this away to a single string. This would give you two pointers to the same memory location, which will make these appear to be equal even though they are supposed to be different strings in your logic.