Implement strcmp
Implement int my_strcmp(const char *s1, const char *s2) that returns a negative value if s1 sorts before s2, zero if they are equal, and a positive value if s1 sorts after s2. Characters must be compared as unsigned char, like the standard function.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Advance while both characters are equal and not the terminator. Then return the difference of the first characters that differ, converted to unsigned char.
#include <stdio.h>
int my_strcmp(const char *s1, const char *s2)
{
const unsigned char *a = (const unsigned char *)s1;
const unsigned char *b = (const unsigned char *)s2;
while (*a && *a == *b) {
a++;
b++;
}
return *a - *b; /* both promote to int: no overflow */
}
Your version is correct, including the important (unsigned char) casts. Converting the pointers once, as above, is equivalent.
The loop stops at the first difference or at the end of s1. You don't need to check *b separately: if s2 ended first, *b is '\0' and differs from *a, so the loop already stopped.
Walk-through: "ab" vs "abc"
| a | b | equal? | action |
|---|---|---|---|
| 'a' | 'a' | yes | advance |
| 'b' | 'b' | yes | advance |
| '\0' | 'c' | stop (end of s1) | return 0 − 99 = −99 (< 0) |
Why the unsigned cast matters: char is signed on x86 and on Arm with some compilers. Without the cast, a byte like 0xE9 ('é' in Latin-1) is −23 and would wrongly sort before 'a'. The C standard says strcmp compares as unsigned char.
Points to mention:
- Only the sign of the result is defined. Never write if (strcmp(a, b) == -1).
- a - b cannot overflow, because both values are 0–255 promoted to int.
- Follow-ups: strncmp (stop after n characters, used for protocol prefixes like "AT+"), case-insensitive compare, and constant-time compare for passwords or MACs so the timing doesn't leak how many characters matched.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
CHECK(my_strcmp("abc", "abc") == 0);
CHECK(my_strcmp("abc", "abd") < 0);
CHECK(my_strcmp("abd", "abc") > 0);
CHECK(my_strcmp("ab", "abc") < 0); /* prefix sorts first */
CHECK(my_strcmp("abc", "ab") > 0);
CHECK(my_strcmp("", "") == 0);
CHECK(my_strcmp("", "a") < 0);
CHECK(my_strcmp("\xE9", "a") > 0); /* 0xE9 > 'a' when unsigned */
CHECK(my_strcmp("A", "a") < 0); /* case-sensitive: 'A' = 65 */
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}