Strings: Comparing

Dave Sinkula 0 Tallied Votes 1K Views Share

How might I write an implementation in C of the standard library function strcmp ? Here's how I might.

See also .

#include <stdio.h>

int mystrcmp(const char *dst, const char *src)
{
   for ( ; *dst && *src; ++src, ++dst )
   {
      if ( *dst != *src )
      {
         break;
      }
   }
   return *dst - *src;
}

int main (void)
{
   const char *text[] = { "hello", "world", "hello", "hell"};
   size_t i, j;
   for ( i = 0; i < sizeof text / sizeof *text; ++i )
   {
      for ( j = i + 1; j < sizeof text / sizeof *text; ++j )
      {
         printf("mystrcmp(\"%s\", \"%s\") = %d\n", text[i], text[j], 
                mystrcmp(text[i], text[j]));
      }
   }
   return 0;
}

/* my output
mystrcmp("hello", "world") = -15
mystrcmp("hello", "hello") = 0
mystrcmp("hello", "hell") = 111
mystrcmp("world", "hello") = 15
mystrcmp("world", "hell") = 15
mystrcmp("hello", "hell") = 111
*/

Dani AI

Generated

A couple of portability and correctness notes for 's implementation. The general approach is fine, but two practical points matter: the C standard treats characters as unsigned when comparing, so casting to unsigned char avoids surprising results on implementations where plain char is signed; and callers must rely only on the sign of strcmp's return value (<0, ==0, >0) rather than any particular magnitude. Also avoid passing NULL pointers — strcmp reads until a NUL byte.

int strcmp_safe(const char *s1, const char *s2)
{
    const unsigned char *a = (const unsigned char *)s1;
    const unsigned char *b = (const unsigned char *)s2;

    while (*a && (*a == *b)) {
        ++a;
        ++b;
    }

    return (int)(*a) - (int)(*b);
}

Why this change: casting to unsigned char preserves the standard ordering for non-ASCII bytes and prevents sign-extension surprises. If you want a normalized result of -1, 0, or 1, compute r = (r > 0) - (r < 0) after the compare. For locale-aware ordering use strcoll; for raw binary data use memcmp. Complexity is linear in the length up to the first differing character or the terminating NUL.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.