Start New Discussion within our Software Development Community

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

See also Strings: Comparing, Case-Insensitive.

#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
*/
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.