🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Comparing Strings with strcmp
Chapter 9, Lecture 10 of the free C programming course: string comparison, return values and sorting
strcmp in C answers a question that the equality operator cannot: do two strings contain the same characters? Writing a == b on two strings compares addresses, not text. This lecture of our free C programming course explains how strcmp walks two strings in step, what its return value really promises, and how to use it for command matching and sorting in embedded C programming.
You will write your own comparison function, sort a list of peripheral names with the standard qsort(), and learn the mistakes that break real firmware. Like every part of this free C tutorial, the code is compiled with gcc -std=c17 -Wall -Wextra and the output shown is the real output.
What You Will Learn
- Why the
==operator is the wrong tool for comparing strings - How strcmp compares character by character and where it stops
- What the return value guarantees: zero, negative or positive, and nothing more
- How to write
ep_strcmp()correctly usingunsigned char - How to sort an array of strings with
qsort()and strcmp - When to prefer
strncmp()and how case-insensitive matching differs
Prerequisites
You need to understand pointers to char, the terminator, and the idea that an array name decays to the address of its first element. The earlier lectures in this free embedded C course cover all three.
Why strcmp in C Beats == for Strings
A string in C is an address. When you write if (cmd == "help") the compiler compares two pointers: where cmd points and where the literal lives. Even if the text is identical, the addresses almost never match, so the test fails. Sometimes it passes by accident when the compiler merges two identical literals, which is the worst outcome because the bug hides until you change optimisation settings.
const char *cmd = read_command();
if (cmd == "help") { /* BUG: compares addresses */ }
if (strcmp(cmd, "help") == 0) { /* correct: compares characters */ }
Remember the idiom strcmp(a, b) == 0 as meaning “a equals b”. It reads backwards at first because the function returns zero on a match, but you will see it in nearly every firmware command parser.
How strcmp in C Compares Two Strings
The prototype is int strcmp(const char *s1, const char *s2);. It examines the strings in lock step, starting at index 0. At each position it asks two questions: are the characters different, and have we reached the terminator? It stops at the first position where either answer is yes.
Two strings are equal only when they match at every position and both reach the terminator together. That second condition is why "app" is not equal to "apple": the first string ends while the second still has characters, and the terminator (value 0) is smaller than any letter.
What the return value promises
| Result | Meaning | Example |
|---|---|---|
| Less than zero | First string sorts before the second | strcmp("apple", "banana") |
| Zero | Strings are identical | strcmp("apple", "apple") |
| Greater than zero | First string sorts after the second | strcmp("zebra", "apple") |
Only the sign is portable
Many books say the function returns the difference of the two differing characters. Some implementations do, others return exactly -1, 0 and 1, and optimised library versions may return other values. The standard guarantees only the sign. Compare the result with 0, never with a specific number such as 1 or the character difference.
Writing Your Own strcmp in C
The loop continues while the current characters are equal and not the terminator. When it exits, the characters at that position are either different or both the terminator. Subtracting them yields the sign you need. One detail is easy to miss: the characters are converted to unsigned char before subtracting. The standard defines strcmp this way, so letters with codes above 127 sort consistently regardless of whether plain char is signed on your platform.
#include <stdio.h>
#include <string.h>
int ep_strcmp(const char *a, const char *b)
{
while (*a != '\0' && *a == *b) {
a++;
b++;
}
return (unsigned char)*a - (unsigned char)*b;
}
static void show(const char *a, const char *b)
{
int r = strcmp(a, b);
printf("strcmp(\"%s\", \"%s\") -> %s\n", a, b,
r < 0 ? "negative" : r > 0 ? "positive" : "zero");
}
int main(void)
{
show("apple", "apple");
show("apple", "banana");
show("zebra", "apple");
show("app", "apple");
show("Zed", "apple");
printf("sign check mine vs libc: %d %d\n",
(ep_strcmp("cat", "car") > 0), (strcmp("cat", "car") > 0));
return 0;
}
$ gcc -std=c17 -Wall -Wextra -o ex10_strcmp ex10_strcmp.c
$ ./ex10_strcmp
Expected output:
strcmp("apple", "apple") -> zero
strcmp("apple", "banana") -> negative
strcmp("zebra", "apple") -> positive
strcmp("app", "apple") -> negative
strcmp("Zed", "apple") -> negative
sign check mine vs libc: 1 1
Study each line. Equal strings give zero. apple comes before banana, so negative. zebra comes after apple, so positive. The prefix case app versus apple is negative because the shorter string hits its terminator first. The last data line is the important one for beginners: Zed is less than apple, because in ASCII every capital letter has a smaller code than every lowercase letter. Comparison is case-sensitive and based on character codes, not on dictionary order. The final line prints 1 and 1, confirming that your function and the library agree on the sign for cat versus car.
Sorting Strings with qsort and strcmp in C
The standard library function qsort() sorts any array if you give it a comparison callback. For an array of const char * the callback receives pointers to the elements, which are pointers to pointers, so you dereference once before calling strcmp. That extra level is the part students find confusing, so read the cast carefully.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int by_name(const void *pa, const void *pb)
{
const char *a = *(const char * const *)pa;
const char *b = *(const char * const *)pb;
return strcmp(a, b);
}
int main(void)
{
const char *periph[] = { "UART", "SPI", "I2C", "ADC", "GPIO", "CAN" };
size_t n = sizeof periph / sizeof periph[0];
qsort(periph, n, sizeof periph[0], by_name);
for (size_t i = 0; i < n; i++)
printf("%zu: %s\n", i, periph[i]);
return 0;
}
$ gcc -std=c17 -Wall -Wextra -o ex10b_sort ex10b_sort.c
$ ./ex10b_sort
0: ADC
1: CAN
2: GPIO
3: I2C
4: SPI
5: UART
The peripheral names now appear in alphabetical order. The same pattern sorts a table of configuration keys so that you can search it with bsearch() later.
Related Comparison Functions
| Function | Compares | Case rule | Where |
|---|---|---|---|
strcmp(a, b) | Until a difference or the terminator | Case-sensitive | Standard C |
strncmp(a, b, n) | At most n characters | Case-sensitive | Standard C |
strcasecmp(a, b) | Until a difference or the terminator | Ignores case | POSIX, not standard C |
memcmp(a, b, n) | Exactly n bytes, terminators ignored | Raw bytes | Standard C |
strncmp is the right tool for prefixes. A modem line such as +CSQ: 21,0 can be recognised with strncmp(line, "+CSQ:", 5) == 0 without caring about the number that follows. memcmp is for binary data such as keys and checksums, where a zero byte is just data and must not end the comparison.
strcmp in Embedded C Programming
Firmware uses strcmp wherever text selects behaviour: console commands, AT responses, configuration keys, and name lookups. A few practical notes:
- Command tables. Store commands in a constant array of structs holding the name and a function pointer, and loop over it with strcmp. That replaces a long chain of
ifstatements and is easy to extend. - Cost. strcmp stops at the first difference, so mismatches are cheap, but a long common prefix makes it slower. For hot paths compare an integer command code instead of text.
- Flash and RAM. Literals normally sit in flash. Comparing against a literal is fine because strcmp only reads. Just never try to modify the literal.
- Timing attacks. Never use strcmp to check secrets such as passwords or authentication tags. It returns as soon as a byte differs, which leaks information through timing. Use a constant-time comparison routine for security checks.
Common Mistakes with strcmp in C
| Mistake | Symptom | Fix |
|---|---|---|
if (a == b) for text | Always false, or true by luck | strcmp(a, b) == 0 |
if (strcmp(a, b)) meaning equal | Logic inverted: runs when strings differ | Compare explicitly with 0 |
| Comparing with a specific value such as 1 | Works on one platform, fails on another | Test only the sign |
| Forgetting the newline from fgets | Command never matches | Strip it before comparing |
| Expecting case-insensitive behaviour | LED does not match led | Normalise case or use strcasecmp |
| Passing a non-terminated buffer | Runaway read | Terminate first or use strncmp |
Best Practices
- Write the check as
strcmp(a, b) == 0, never as a bare truthiness test; this idiom is the heart of strcmp in C. - Keep command names in one table so that adding a command is a one-line change.
- Normalise input (trim spaces, remove newline, convert case) in one place before any comparison.
- Declare comparison parameters as
const char *. - Use
strncmpfor prefix checks andmemcmpfor binary data.
Key takeaways
- Use strcmp, not
==, to compare string contents. - Zero means equal; the sign gives the ordering; the exact magnitude is not portable.
- Comparison uses character codes, so uppercase sorts before lowercase in ASCII.
qsortwith a strcmp callback sorts an array of strings; dereference the element pointer once.- Do not use strcmp for secrets.
Conclusion
Using strcmp in C is easy, yet the function has a surprising number of rules. Keep three in mind and you will avoid most bugs: compare contents with strcmp, trust only the sign of the result, and remember that the terminator takes part in the comparison. In the next lecture we cover copying strings safely, the operation behind more security bugs than any other in C.
Frequently Asked Questions
Why does strcmp return 0 when strings are equal?
Zero means no difference was found, which fits the ordering model: negative, zero, positive. It is the opposite of boolean truth, so always compare the result with 0.
Is strcmp case-sensitive?
Yes. ‘A’ and ‘a’ have different codes, so they differ. Use the POSIX strcasecmp or convert both strings to one case when you need case-insensitive matching.
Can I rely on the value being the character difference?
No. Only the sign is guaranteed by the C standard. Never write code that depends on the magnitude.
How do I compare only the first few characters?
Use strncmp(a, b, n). It stops after n characters or at a terminator, whichever comes first.
Which is better for binary data, strcmp or memcmp?
memcmp. Binary data can contain zero bytes, which would stop strcmp early, and memcmp compares exactly the number of bytes you give.
Is strcmp safe for checking passwords?
No. It exits at the first mismatch, so the time taken reveals how many leading characters were correct. Use a constant-time comparison for secrets.
Topics Covered
Learn C Programming for Free
Next: copying strings with strcpy and the safer alternatives every embedded C programmer must know. Keep going with the free embedded C course.

2 Comments