Arrays & Strings · beginner · ~8 min

strcmp and string comparison

Compare strings safely; understand the return value.

Lesson

strcmp(a, b) returns 0 if the strings are equal, a negative value if a sorts before b, and a positive value if a sorts after. It does not return a boolean — use strcmp(a, b) == 0 for equality.

For fixed-prefix comparisons, use strncmp(a, b, n). For case-insensitive comparison, use strcasecmp (POSIX) — there is no standard C equivalent.

Code examples

if (strcmp(input, "quit") == 0) {
    return 0;
}

Common mistakes

  • if (strcmp(a, b)) is "true if NOT equal" — confusing. Always compare to 0 explicitly.
  • Comparing C strings with ==: that compares pointers, not contents.