AlgoInsight

Q&A

How to compare strings using strcmp() function in C

By AlgoInsight Team2026-06-07stringsc

Overview

In C a "string" is a null-terminated char array, and there's no built-in string type or == comparison of contents. strcmp() is the standard library function for comparing string values. Understanding its three-way return (negative/zero/positive) and why == doesn't work is fundamental C knowledge.

graph TD
    A["strcmp(s1, s2)"] --> B[Compare byte by byte]
    B --> C{First differing char?}
    C -->|s1 < s2| D[returns negative]
    C -->|equal through '\0'| E[returns 0]
    C -->|s1 > s2| F[returns positive]
    style E fill:#1e1b4b,color:#fff

Signature

#include <string.h>
int strcmp(const char *s1, const char *s2);

The magnitude isn't standardized as ±1 - only the sign is meaningful. (It's typically the difference of the first differing characters.)

Basic Usage

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

int main() {
    char a[] = "apple";
    char b[] = "apple";
    char c[] = "banana";

    if (strcmp(a, b) == 0) printf("a equals b\n");      // prints
    if (strcmp(a, c) < 0)  printf("a comes before c\n"); // prints ('a' < 'b')

    printf("%d\n", strcmp("abc", "abd"));   // negative ('c' < 'd')
    printf("%d\n", strcmp("abc", "ab"));    // positive (longer, extra char)
    return 0;
}

Why You Can't Use ==

char a[] = "apple";
char b[] = "apple";
if (a == b) { /* almost always FALSE */ }

a == b compares the addresses of the two arrays, not their characters. Two separate arrays live at different addresses even with identical contents. Always use strcmp for content comparison.

How It Works (lexicographic order)

strcmp walks both strings in lockstep, comparing the byte values of characters (their char/ASCII codes). At the first position where they differ, it returns the sign of s1[i] - s2[i]. If one string ends ('\0') while the other continues, the shorter one is "less." This is dictionary-style ordering based on character codes (note: uppercase letters sort before lowercase in ASCII).

Related Functions

Function Purpose
strncmp(s1, s2, n) Compare only the first n characters (safer with bounded data)
strcasecmp / _stricmp Case-insensitive compare (POSIX / Windows)
memcmp(a, b, n) Compare n raw bytes (not null-terminated)
strcoll Locale-aware comparison
strncmp("apple", "apricot", 2);   // 0 - first 2 chars ("ap") match

Safety Notes

Why This Matters in Interviews

C/systems interviews use strcmp to verify you understand C strings: that they're null-terminated arrays, that == compares pointers (a classic bug), and that strcmp returns a three-way sign (not a boolean). Knowing strncmp for bounded/safe comparison and the case-insensitive variants shows practical awareness. Explaining lexicographic comparison via character codes is the conceptual core.

Common Pitfalls

References

More answers