Search code examples
cstrcmpstring.h

I do not understand strcmp results


this is my implementation of strcmp ,

   #include <stdio.h>
   #include <string.h>

   int ft_strcmp(const char *s1, const char *s2)
   {
       while (*s1 == *s2)
       {
           if (*s1 == '\0')
              return (0);
          s1++;
          s2++;
      }
      return (*s1 - *s2);
  }

  int main()
  {
      char    s1[100] = "bon";
      char    s2[100] = "BONN";
      char    str1[100] = "bon";
      char    str2[100] = "n";
      printf("%d\n", ft_strcmp(s1, s2));
      printf("%d\n", ft_strcmp(str1, str2));
      return (0);
  }

from the book kernighan and Ritchie but i use a while loop, instead of the for, i ve tested it many times and my strcmp geaves the same results as the original strcmp, but i do not understand the results , i rode the man: "The strcmp() and strncmp() functions lexicographically compare the null-terminated strings s1 and s2." what does lexicography means ? "return an integer greater than, equal to, or less than 0, according as the string s1 is greater than, equal to, or less than the string s2." i understand this part but my questions are how can it come up with such results:

32
-12

s1 looks < s2 for me so how and why do i get 32 and how the calcul is made ? str1 looks > str2 for me, how and why do i get -12 and how the calcul is made. I ve compile it with the real STRCMP and i get the Same results..

last question why do i need to compare *s1 to '\0' won't it work fine without ?

thank you for your answers i m confused..


Solution

  • 1) K&R are comparing the ascii values of those chars, that's why you get 32 and -12, check out an ascii table and you'll understand.

    2)If you don't check for \0 , how can you know when the string end? That's the c strings terminator.