Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

memcmp — C23 byte-representation comparison

`memcmp(s1, s2, n)` from `<string.h>` lexicographically compares the first `n` bytes of two object representations, interpreting every byte as `unsigned char`. It returns zero if all are equal; otherwise it returns a value whose sign is the difference of the first unequal pair. The sign, not the exact magnitude, is guaranteed.

Version: C23

Syntax

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

memcmp(s1, s2, n) from <string.h> lexicographically compares the first n bytes of two object representations, interpreting every byte as unsigned char. It returns zero if all are equal; otherwise it returns a value whose sign is the difference of the first unequal pair. The sign, not the exact magnitude, is guaranteed.

The example compares 0x80 with 0x7F after a common 0x00 byte. Real calls print 1 1 0: the first buffer is greater under unsigned-byte ordering, a buffer equals itself, and the one-byte common prefixes compare equal.

This compares representations, not semantic values: structure padding takes unspecified values after stores, unions and spare bytes can also mislead, and distinct representations can denote values that compare equal. Compare fields rather than whole structures when defining logical keys. n must fit within both accessible objects; for n == 0 the result is zero, but C23 still requires valid values for both pointers.

Examples

#include <stdio.h>
#include <string.h>
int main(void){const unsigned char a[]={0x00,0x80,0xFF};const unsigned char b[]={0x00,0x7F,0xFF};printf("%d %d %d\n",memcmp(a,b,3)>0,memcmp(a,a,3)==0,memcmp(a,b,1));return 0;}

Result

1 1 0

The example compares `0x80` with `0x7F` after a common `0x00` byte. Real calls print `1 1 0`: the first buffer is greater under unsigned-byte ordering, a buffer equals itself, and the one-byte common prefixes compare equal.

Sources