strncmp()

Updated: April 19, 2023

Compare two strings, up to a given length

Synopsis:

#include <string.h>

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

Arguments:

s1, s2
The strings that you want to compare.
n
The maximum number of characters that you want to compare.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The strncmp() function compares up to n characters from the strings pointed to by s1 and s2.

Returns:

< 0
s1 is less than s2.
0
s1 is equal to s2.
> 0
s1 is greater than s2.

Examples:

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

int main( void )
  {
    printf( "%d\n", strncmp( "abcdef", "abcDEF", 10 ) );
    printf( "%d\n", strncmp( "abcdef", "abcDEF",  6 ) );
    printf( "%d\n", strncmp( "abcdef", "abcDEF",  3 ) );
    printf( "%d\n", strncmp( "abcdef", "abcDEF",  0 ) );
    return EXIT_SUCCESS;
  }

produces the output:

1
1
0
0

Classification:

ANSI, POSIX 1003.1

Safety:  
Cancellation point No
Interrupt handler Yes
Signal handler Yes
Thread Yes