Coding

strcmp in C: How to Compare Strings Correctly

strcmp in C compares two null-terminated strings and returns 0 if they are equal, a negative number if the first comes before the second, and a positive number if it comes after. Declared in <string.h>, it is the correct way to test string equality, because == compares addresses, not characters.

#include <stdio.h>
#include <string.h>

int main(void) {
    const char *answer = "yes";
    if (strcmp(answer, "yes") == 0) {
        puts("equal");
    }
    return 0;
}

The signature and what it returns

int strcmp(const char *lhs, const char *rhs);

Both arguments must point to null-terminated byte strings. The result depends on the first position where the two strings differ. The documented rule is that the sign of the result is the sign of the difference between that first pair of differing characters, both interpreted as unsigned char.

ResultMeaning
Negativelhs appears before rhs in lexicographical order
0the strings are equal
Positivelhs appears after rhs in lexicographical order

Only the sign is guaranteed. The documentation does not promise a particular magnitude, so strcmp("a", "c") may return -2 on one system and -1 on another. Test the result against 0, or against being less than or greater than 0, and never against a specific nonzero number such as -1.

Why == does not compare strings

A string literal or a char array turns into a pointer to its first character when you use it in a comparison. So == asks whether two pointers hold the same address. Two strings with identical text stored in different places are not equal under ==:

char first[] = "hello";
char second[] = "hello";

if (first == second) {
    puts("same address");      // not printed: two separate arrays
}
if (strcmp(first, second) == 0) {
    puts("same contents");     // printed
}

Compilers sometimes merge identical string literals, so "hello" == "hello" may appear to work. That is an optimization you cannot rely on, and it breaks as soon as one string comes from user input, a file or a buffer.

How to check whether two strings are equal

Compare the result to zero. Writing !strcmp(a, b) works too, but it reads as "not compare", which is the opposite of what people expect, so strcmp(a, b) == 0 is clearer.

if (strcmp(command, "quit") == 0) {
    /* strings are equal */
}
if (strcmp(command, "quit") != 0) {
    /* strings differ */
}

How to sort or order strings

Because strcmp returns a negative, zero or positive int, it fits the comparison function that qsort expects. The elements of an array of char * are pointers, so the callback receives pointers to pointers and has to dereference them once:

#include <stdlib.h>
#include <string.h>

static int compare_names(const void *left, const void *right) {
    const char *const *a = left;
    const char *const *b = right;
    return strcmp(*a, *b);
}

int main(void) {
    const char *names[] = { "pear", "Apple", "fig" };
    qsort(names, 3, sizeof names[0], compare_names);
    /* names is now: "Apple", "fig", "pear" */
    return 0;
}

Note the order: "Apple" comes first even though "fig" and "pear" would sort earlier in a dictionary if case were ignored. In ASCII, uppercase letters have lower byte values than lowercase letters, and strcmp compares raw byte values.

strncmp: compare only the first n characters

int strncmp(const char *lhs, const char *rhs, size_t count);

strncmp compares at most count characters and stops at a null character, so characters after it are never examined. It returns zero if the first count characters match, or if count is zero. That makes it the usual tool for prefix tests:

const char *line = "GET /index.html";
if (strncmp(line, "GET ", 4) == 0) {
    puts("starts with GET");
}

Passing a length that is too large is not a safe way to "be careful". The behavior is undefined if the function reads past the end of either array, and also if either argument is a null pointer.

Case-insensitive comparison

Standard C has no case-insensitive version of strcmp. Two common non-standard options exist: strcasecmp in <strings.h> on POSIX systems, and _stricmp on Windows compilers. If you need portable code, convert both strings to one case with tolower from <ctype.h> while you compare character by character, and cast each char to unsigned char before passing it.

Locale and byte order

strcmp is not locale-sensitive. The Linux man page states that the locale is not taken into account and points to strcoll for locale-aware comparison. The man page also describes strcmp as behaving as if it called memcmp over the shorter length plus the terminating null byte. In practice this means bytes above 127, as found in UTF-8 text, compare by their unsigned byte values, not by the alphabetical order of the language. If you need to sort names in German or Swedish the way a person expects, use strcoll after setting the locale with setlocale.

Common mistakes

  • Using == on strings. It compares addresses. Use strcmp(a, b) == 0.
  • Passing a string that is not null-terminated. The behavior is undefined. This often happens with a buffer filled by strncpy, which does not add a terminator if the source is as long as the limit. Terminate the buffer yourself, or read input with fgets as described in fgets in C: how to read a line of input safely.
  • Forgetting the newline from fgets. A line read with fgets usually ends in \n, so strcmp(line, "yes") fails while strcmp(line, "yes\n") succeeds. Strip the newline first, for example with line[strcspn(line, "\n")] = '\0';.
  • Passing a null pointer. strcmp(NULL, "x") is undefined behavior. Check pointers that can be null before comparing.
  • Testing for exactly -1 or 1. The magnitude is not specified. Compare with < 0 or > 0.
  • Using the result as a boolean for "equal". if (strcmp(a, b)) is true when the strings are different.

If the comparison gives the wrong answer

Print both strings between delimiters, for example printf("[%s] [%s]\n", a, b);. Trailing spaces, a trailing newline or a carriage return (\r) from a Windows text file show up inside the brackets and explain most "these look identical" bugs. If the program crashes inside strcmp, one of the pointers is null, uninitialized, or points to a buffer without a terminator.

Frequently asked questions

What does strcmp return in C?
strcmp returns zero if the two strings are equal, a negative value if the first string comes before the second in lexicographical order, and a positive value if it comes after. Only the sign is specified by the C standard library documentation, so the exact number can differ between implementations.
Why can't I compare strings with == in C?
A string in C is an array of characters, and in a comparison it decays to a pointer. The == operator compares those two pointers, which are equal only if both point to the same address. It does not look at the characters. Use strcmp to compare the contents.
Is strcmp case sensitive?
Yes. strcmp compares byte values, so 'a' and 'A' differ. The C standard library has no case-insensitive function. POSIX systems provide strcasecmp in <strings.h>, and Windows compilers provide _stricmp, but neither is part of standard C.
What is the difference between strcmp and strncmp?
strncmp takes a third argument, count, and compares at most that many characters. It also stops at the first null character. If count is zero, it returns zero. Use it to compare a prefix, or when a buffer might not be null-terminated within a known size.
Does strcmp compare strings alphabetically?
Not by the rules of any language. It compares bytes as unsigned char values and ignores the locale, so in ASCII every uppercase letter sorts before every lowercase letter. For locale-aware ordering, C provides strcoll.

Sources