Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
strcmp.c
Go to the documentation of this file.
1 #include <string.h>
2 
3 /*
4  * PJ: my own strcmp implementation
5  *
6  * strcmp 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)
10  */
11 
12 int strcmp(const char* s1, const char* s2)
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 w/ -1
23  if(s1 != NULL && s2 != NULL)
24  {
25  // iterate through strings until they don't match or s1 ends (null-term)
26  for(; *s1 == *s2; ++s1, ++s2)
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(r != 0)
37  {
38  r = *(const char*)s1 - *(const char*)s2;
39  }
40  }
41 
42  return r;
43 }
#define NULL
Definition: stddef.h:15
int strcmp(const char *s1, const char *s2)
Compares two null-terminated byte strings lexicographically.
Definition: strcmp.c:12