Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
strncmp.c File Reference
#include <string.h>
Include dependency graph for strncmp.c:

Go to the source code of this file.

Functions

int strncmp (const char *s1, const char *s2, size_t n)
 Compares at most n characters of two possibly null-terminated arrays. More...
 

Function Documentation

◆ strncmp()

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

Compares at most n characters of two possibly null-terminated arrays.

Compares at most count characters of two possibly null-terminated arrays. The comparison is done lexicographically.

The behavior is undefined when access occurs past the end of either array s1 or s2. The behavior is undefined when either s1 or s2 is the null pointer.

Parameters
s1pointers to the null-terminated byte strings to compare
s2pointers to the null-terminated byte strings to compare
nmaximum number of characters to compare
Returns
Negative value if s1 appears before s2 in lexicographical order. Zero if s1 and s2 compare equal, or if n is zero. Positive value if s1 appears after s2 in lexicographical order.

Definition at line 12 of file strncmp.c.

13 {
14  int r = -1;
15 
16  if(s1 == s2)
17  {
18  // short circuit - same string
19  return 0;
20  }
21 
22  // I don't want to panic with a NULL ptr - we'll fall through and fail
23  if(s1 != NULL && s2 != NULL)
24  {
25  // iterate through strings until they don't match, s1 ends, or n == 0
26  for(; n && *s1 == *s2; ++s1, ++s2, n--)
27  {
28  if(*s1 == 0)
29  {
30  r = 0;
31  break;
32  }
33  }
34 
35  // handle case where we didn't break early - set return code.
36  if(n == 0)
37  {
38  r = 0;
39  }
40  else if(r != 0)
41  {
42  r = *s1 - *s2;
43  }
44  }
45 
46  return r;
47 }
#define NULL
Definition: stddef.h:15

References NULL.

Referenced by strnstr().

Here is the caller graph for this function: