title: memcmp C implementation - any logical errors with this one
body: <p>memcmp C implementation - any logical errors with this one?</p>
  
  <p>I was going looking for an implementation of memcmp(), I found this code snippet, but it is clearly marked that there is 1 logical error with the code snippet. Could you help me find the logical error.</p>
  
  <p>Basically, I tested this code against the string.h library implementation of memcmp() with different inputs, but the expected output is always the same as the library version of the function.</p>
  
  <p>Here is the code snippet:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  int memcmp_test(const char *cs, const char *ct, size_t n)
  {
    size_t i;   
  
    for (i = 0; i &lt; n; i++, cs++, ct++)
    {
      if (*cs &lt; *ct)
      {
        return -1;
      }
      else if (*cs &gt; *ct)
      {
        return 1;
      }
      else
      {
        return 0;
      }
    }
  } 
  
  
  
  int main()
  {
      int ret_val = 20; //initialize with non-zero value 
  
      char *string1 = "china";
      char *string2 = "korea";
  
      ret_val = memcmp_test(string1,string2,5); 
  
      printf ("ret_val is = %d",ret_val);
  
      getchar();
      return 0;
  }
  </code></pre>
  
  <p>I ran the program with the two example strings and the program would return just after the comparison of the first characters of the two strings. ret_val is -1 in the above case.</p>
  
  <p>The definition of memcmp() which the above code snippet should conform to is:</p>
  
  <p>The definition of the ‘C’ Library function memcmp is
  int memcmp(const char *cs, const char *ct, size_t n)</p>
  
  <p>Compare the first n characters of cs with the first n characters of ct. 
  Return &lt; 0 if cs &lt; ct. 
  Return > 0 if cs > ct. 
  Return 0 if cs == ct. </p>
  
  <p>There is definitely on LOGICAL error, could you help me find it.</p>