1

How about comparing two strings with equality operator. I saw in GNOME glib library also. They compare two strings with == operator. Here is the code:

/* Code from Singly Linked List - gslist.c*/


GSList*
g_slist_find (GSList        *list,
              gconstpointer  data)  // Here gconstpointer is `const void*`
{
  while (list)
    {
      if (list->data == data)    // What is compare here?
        break;
      list = list->next;
    }

  return list;
}

So, Is glib code works or not always?

Ashish Rawat
  • 3,363
  • 5
  • 29
  • 35
  • 1
    You've asked whether or not it works, then you say it works. Which is it? – Robert Harvey Aug 01 '13 at 19:54
  • *"This also works fine"* Erm, no, not really. You don't see the flaw in your test. That string is stored once and both pointers point to the same memory location. You are comparing addresses, not strings. – Ed S. Aug 01 '13 at 19:56
  • `if(a == b)` is working find because of compiler optimization and both `a`, `b` points to same location because. Its could be possible because you assigns strings statically at coding time. But really when you compares strings using `==` you actually comparing addresses of strings. Correct way to compare string is `strcmp()` function. – Grijesh Chauhan Aug 01 '13 at 20:21
  • The linked question is very nicely answered by H2CO3. – Grijesh Chauhan Aug 01 '13 at 20:22
  • 1
    In the Glib code you posted, `list->data` and `data` are pointers to `void`. The `==` is comparing pointer values. What makes you think the `==` it's doing a string comparison? (It's possible to reduce string comparison to pointer comparison using [string interning](http://en.wikipedia.org/wiki/String_interning), but that requires extra work to ensure that, for example, you don't have two copies of the same string at different addresses.) – Keith Thompson Aug 01 '13 at 20:25

1 Answers1

3

The == operator when used on char* will simply check to see if they point to the same memory address. Sure every string pair which compares to true with == will also compare true with strcmp. However the reverse is simply not true. It is very possible that two strings are lexically equivalent but reside at different addresses

For example

char* p1 = "hello world";

// p2 will point to the same address as p1.  This is how pointer 
// assignment work 
char* p2 = p1;
printf ("%s\n", p1 == p2 ? "true" : "false")            // true
printf ("%s\n", strcmp(p1, p2) == 0 ? "true" : "false") // true

// the addressed return by malloc here will not be the address
// of p1. 
char* p3 = malloc(strlen(p1) + 1);
strcpy(p3, p2);
printf ("%s\n", p1 == p3 ? "true" : "false")            // false
printf ("%s\n", strcmp(p1, p3) == 0 ? "true" : "false") // true
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454