strncmp(3)

strncmp3

Nonstrings compare

Usage

#include <string.h>  // see memory.h(3head)

int strncmp(const char s1[], const char s2[], size_t n);

Library

Standard C library (libc, -lc)

Overview

The strncmp() function is similar to strcmp(3), except it compares only the first (at most) n bytes of s1 and s2.

It is equivalent to

memcmp(s1, s2, MIN(MIN(strnlen(s1,n),strnlen(s2,n))+1, n))

Return value

See memcmp(3).

Attributes

For an explanation of the terms used in this section, see attributes(7).

InterfaceAttributeValue
strncmp()Thread safetyMT-Safe

Examples

The program below can be used to demonstrate the operation of strncmp().

$ ./strncmp ABC AB 3;
<strn1> is greater than <strn2> (67)
$ ./strncmp ABC AB 2;
<strn1> and <str2> are equal in the first 2 bytes

Program source

// strncmp.c
// Licensed under GNU General Public License v2 or later.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char *argv[])
{
    int res;
    if (argc != 4) {
        fprintf(stderr, "Usage: %s <strn1> <strn2> <n>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    res = strncmp(argv[1], argv[2], atoi(argv[3]));
    if (res == 0) {
        printf("<strn1> and <strn2> are equal");
        printf(" in the first %d bytes\n", atoi(argv[3]));
        printf("\n");
    } else if (res < 0) {
        printf("<strn1> is less than <strn2> (%d)\n", res);
    } else {
        printf("<strn1> is greater than <strn2> (%d)\n", res);
    }
    exit(EXIT_SUCCESS);
}

Releases

19 releases since Debian 1.1 (Buzz); the text changed 13 times.

  1. 1.1–2.2
  2. 3.0
  3. 3.1
  4. 4.0
  5. 5.0
  6. 6.0
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. Arch

Standards

C11, POSIX.1-2008.

History

POSIX.1-2001, C89, SVr4, 4.3BSD.

From man-pages 6.19-1 in Arch Linux 2026-11-01. Parsed by carta from the page's man source.