Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

wcsncmp — bounded wide-character comparison

wcsncmp compares at most n wchar_t elements. Its result describes ordering or equality of the compared portion, not necessarily entire strings.

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

Syntax

#include <wchar.h>
int wcsncmp(const wchar_t *s1, const wchar_t *s2, size_t n);

wcsncmp, declared in <wchar.h>, compares at most n wide characters. Characters after L'\0' are not compared. The first differing pair in the comparison determines the sign of the result, but C does not guarantee that the implementation stops reading at that pair. The limit counts wchar_t elements, not bytes.

A negative, zero, or positive result means the compared portion is respectively less, equal, or greater. Test the sign, not exact values of -1 or 1. Ordering follows character values, not locale collation rules.

For n == 0, the result is zero; still supply valid pointers. Each array must provide at least n elements or contain an L'\0' terminator within its available elements. Do not rely on an early difference to pass a shorter, unterminated array. Equal prefixes do not prove whole-string equality.

Examples

#include <stdio.h>
#include <wchar.h>

int main(void)
{
    const wchar_t a[] = L"cat";
    const wchar_t b[] = L"car";

    printf("prefix_equal=%d\n", wcsncmp(a, b, 2) == 0);
    printf("whole_equal=%d\n", wcsncmp(a, b, 3) == 0);
    printf("zero_equal=%d\n", wcsncmp(a, b, 0) == 0);
    return 0;
}

Result

prefix_equal=1
whole_equal=0
zero_equal=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