liveBook · Manning

Strcmp

As explained in Modern C, Third Edition

strcmp is a C standard-library function that lexicographically compares two null-terminated strings.

strcmp compares two null-terminated character arrays in lexicographic order. It stops when it encounters the first 0 character in either array, so both arguments must be valid strings. section 6.1.5

Testing an exact copy

A program can compare a copied program name with its source using if (!strcmp(name, argv[0])). The zero result makes the condition true when the strings compare equal. section 6.1.5

size_t strlen(char const s[static 1]);
char*  strcpy(char target[static 1], char const source[static 1]);
char*  strdup(char const s[static 1]);
char*  strndup(char const s[static 1], size_t n);
signed strcmp(char const s0[static 1], char const s1[static 1]);
signed strcoll(char const s0[static 1], char const s1[static 1]);
char* strchr(const char s[static 1], int c);
size_t strspn(const char s1[static 1], const char s2[static 1]);
size_t strcspn(const char s1[static 1], const char s2[static 1]);

The declaration places strcmp alongside related string and memory functions, showing its const string parameters and signed result. section 6.1.5

Unlike strcoll, strcmp does not account for language-specific environment settings; characters such as ä may therefore compare differently from locale-aware expectations. section 6.1.5

Passing an array without a terminating 0 violates the string-function requirement and can cause out-of-bounds access or other program failures. section 6.1.5

How Modern C, Third Edition covers it

How deep it goes
Explains lexicographic comparison, stopping at the first terminator, related functions, and termination failures.
Examples
Uses a copied program name and an if (!strcmp(...)) equality check.
What it assumes
Assumes familiarity with character arrays and requires understanding that strings end with a 0 character.
What you can do after
Apply strcmp to compare valid null-terminated strings and test whether two strings compare equally.
How it connects
Relates strcmp to memcmp, strcoll, strlen, strcpy, strchr, strspn, and strcspn.

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.