Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

strncmp — byte-limited comparison

strncmp compares at most n bytes, stopping at '\0'. Equal prefixes do not establish equality of entire strings.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <string.h>
int strncmp(const char *s1, const char *s2, size_t n);

strncmp from <string.h> compares at most n bytes; bytes after \0 are not compared. n has type size_t.

The result is negative, zero, or positive. Its sign follows the first differing pair, interpreted as unsigned char; do not assume -1 or 1. This is bytewise, not linguistic, comparison.

Supply valid pointers and an accessible comparison range. Without \0, provide n accessible bytes. Access beyond an object causes undefined behavior. With n == 0, the result is zero, but NULL remains invalid. memcmp also compares bytes after zero; strcmp has no n limit.

Examples

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

int main(void)
{
    printf("%d\n", strncmp("cat", "car", 2) == 0);
    printf("%d\n", strncmp("cat", "catfish", 4) < 0);
    printf("%d\n", strncmp("a\0x", "a\0y", 3) == 0);
    return 0;
}

Result

1
1
1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources