Jump to: navigation, search

Prototype

Declared in string.h

The C89/C99 prototype is:

int memcmp(const void * s1, const void * s2,size_t n);

Description

The memcmp() function compares the first n characters of the object pointed to by s1 to the first n characters of the object pointed to by s2.

Beware: Padding is indeterminate, strings need not fill their allotted space.

Return value

The memcmp() function returns an integer greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2.

Implementation

In standard C, this can be implemented as:

#include <stddef.h> /* size_t */
int memcmp(const void* s1, const void* s2,size_t n)
{
    const unsigned char *p1 = s1, *p2 = s2;
    while(n--)
        if( *p1 != *p2 )
            return *p1 - *p2;
        else
            p1++,p2++;
    return 0;
}

Compilable unit, portable C90 in implementation namespace; public domain; past reviewers: none; current reviews: none

References

The C Standard, 7.21.4.1 (C99 numbering)

Personal tools