strcmp is a standard C library function, declared in <string.h>, that compares two strings. It works through both strings one character at a time and stops at the first difference or at the terminator. Its return value tells you whether the strings match and, if they do not, which one sorts first. C++ programs can call the same function as std::strcmp from <cstring>.
The signature
int strcmp(const char *s1, const char *s2);
Both arguments are pointers to null-terminated strings. strcmp reads them but does not change them.
What the return value means
- 0: the strings are equal.
- Less than 0:
s1sorts befores2. - Greater than 0:
s1sorts afters2.
The C standard guarantees only the sign of the result. Do not rely on exact values such as -1 or 1, because they differ between libraries.
Characters are compared as unsigned char values. For plain ASCII text, this means uppercase letters sort before lowercase ones, so "A" is less than "a".
A working example
#include <stdio.h>
#include <string.h>
int main(void) {
const char *a = "apple";
const char *b = "apple";
const char *c = "banana";
if (strcmp(a, b) == 0) {
printf("a and b match\n");
}
if (strcmp(a, c) < 0) {
printf("a sorts before c\n");
}
if (strcmp(c, a) > 0) {
printf("c sorts after a\n");
}
return 0;
}
Output:
a and b match
a sorts before c
c sorts after a
How the comparison stops
strcmp("apple", "apple pie")returns a negative value. The first string ends earlier, and the terminator’s code (0) is lower than the code of any printable character, so the shorter string sorts first.strcmp("Apple", "apple")returns a negative value, because'A'(65) has a lower code than'a'(97).
A common mistake
Because 0 means equal, a non-zero result counts as true in an if statement. A common mistake is to write this and expect it to run when the strings match:
if (strcmp(input, "yes")) {
printf("The answer is yes.\n");
}
It runs when the strings differ. To test for a match, compare the result with 0:
if (strcmp(input, "yes") == 0) {
printf("The answer is yes.\n");
}
Other things to know
- Both strings must be null-terminated. Otherwise
strcmpreads past the end of the array. - Passing a null pointer to
strcmpis undefined behavior. strncmp(s1, s2, n)compares at mostncharacters, which is useful when you only need to check the start of a string.- Using
==on two C strings compares their addresses, not their text, which is whystrcmpexists. Readers from Java often ask, “Should I use equals () or == for string compare?” For C-style strings, the answer isstrcmp. Forstd::stringin C++, the answer is==.
A complete program built around strcmp is covered in How to Write a C Program to Compare Two Strings. For the bigger picture across both string types in C++, see how to compare two strings in c.