Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
strncmp.c
Go to the documentation of this file.
1
#include <
string.h
>
2
3
/*
4
* PJ: my own strncmp implementation
5
*
6
* strncmp with short-circuit support: very common when you have const strings
7
* combined by the compiler.
8
* Otherwise we compare the strings as normal
9
* We bail out when s1 ends (null-term) or n bytes have been analyzed
10
*/
11
12
int
strncmp
(
const
char
* s1,
const
char
* s2,
size_t
n)
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
}
string.h
NULL
#define NULL
Definition:
stddef.h:15
strncmp
int strncmp(const char *s1, const char *s2, size_t n)
Compares at most n characters of two possibly null-terminated arrays.
Definition:
strncmp.c:12
src
string
strncmp.c
Generated by
1.8.15