Arrays & Strings · beginner · ~8 min
Compare strings safely; understand the return value.
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.
if (strcmp(input, "quit") == 0) {
return 0;
}
if (strcmp(a, b)) is "true if NOT equal" — confusing. Always compare to 0 explicitly.==: that compares pointers, not contents.