Memcmp returns a positive number if first
> second
, negative for first
< second
, and 0
if both byte sequences are equal. This is done lexicographically, this is, the function decides at the first encountered difference.
The easiest way to compare both strings is:
int my_memcmp(
const unsigned char *first,
const unsigned char *second,
size_t sz)
{
while (sz--) {
int cmp = *first++ - *second++;
if (cmp == 0) continue;
/* return the difference of the first
* pair that differs */
return cmp;
}
return 0;
}
if you want to maintain the same prototype than the standard libray version, the you need to use void *
pointers, and convert them internally to unsigned char *
, as in:
int my_memcmp(
const void *_first,
const void *_second,
size_t sz)
{
const unsigned char
*first = _first,
*second = _second;
while (sz--) {
int cmp = *first++ - *second++;
if (cmp == 0) continue;
return cmp;
}
return 0;
}
(you don't need to use const void *
, as a void *
is not dereferrable, and so, it is not modifiable)
Edit: the const
modifiers added allow the calling routine to know that the target value cannot be modified by this routine, and this allows the compiler to optimize, based on that. (as the const void *
can appear superfluous, because void
type cannot be dereferenced, or accessed, if you convert a const void *
to another kind of pointer, you'll get an error if you don't use a pointer to const
also. This makes the const
keyword recommendable even for void
type.