C String strcmp() Function

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
<string.h>

What You’ll Learn

The strcmp() function compares two C-strings lexicographically—character by character using byte values. It tells you whether strings are equal or which one sorts first. It is one of the most frequently used functions in C.

01

Compare

s1 vs s2.

02

0 = Equal

Exact match.

03

< 0 / > 0

Less / greater.

04

Case Sensitive

a ≠ A.

05

string.h

Standard C.

06

vs strncmp

Limit bytes.

Definition and Usage

strcmp walks both strings in parallel. At the first position where bytes differ, it compares those bytes as unsigned char values and returns a negative or positive result. If all compared bytes match and both strings end together, the result is zero.

Use strcmp(s1, s2) == 0 to test equality. For sorting, the sign of the return value is what matters—do not rely on the exact integer (such as -1 or 1) being the same on every platform.

💡
Beginner Tip

Never write if (strcmp(a, b)) when you mean “are equal”—zero is falsy in C, so that condition means “not equal.” Always use == 0 for equality.

📝 Syntax

Standard C declaration:

C
int strcmp(const char *s1, const char *s2);

Parameters

  • s1 — first null-terminated string.
  • s2 — second null-terminated string.

Return Value

  • 0 — strings are equal.
  • < 0s1 is less than s2.
  • > 0s1 is greater than s2.

Header

  • #include <string.h>

⚡ Quick Reference

s1s2strcmp result
"apple""apple"0 (equal)
"apple""banana"< 0 (apple before banana)
"Hello, World!""Hello, Universe!"> 0 ('W' > 'U')
"Hello""hello"< 0 ('H' < 'h')
equality testany pairstrcmp(a, b) == 0
Equal?
strcmp(a, b) == 0

Exact match

Less?
strcmp(a, b) < 0

a before b

Greater?
strcmp(a, b) > 0

a after b

Ignore case
strcasecmp(a, b)

POSIX

Examples Gallery

Compile with gcc strcmp.c -std=c11 -o strcmp. Each program includes <string.h>.

📚 Getting Started

Compare strings and interpret the return value.

Example 1 — Compare Two Different Strings

"Hello, World!" vs "Hello, Universe!"—they differ at 'W' vs 'U'.

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

int main(void) {
    const char *str1 = "Hello, World!";
    const char *str2 = "Hello, Universe!";

    int result = strcmp(str1, str2);

    if (result == 0) {
        printf("The strings are equal.\n");
    } else if (result < 0) {
        printf("str1 is less than str2.\n");
    } else {
        printf("str1 is greater than str2.\n");
    }

    return 0;
}

How It Works

Both strings share "Hello, ". The next bytes are 'W' (87) and 'U' (85). Since 87 > 85, strcmp returns a value greater than zero.

Example 2 — Test for Equality

Use == 0 when both strings must match exactly.

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

int main(void) {
    const char *expected = "admin";
    const char *entered = "admin";

    if (strcmp(entered, expected) == 0) {
        printf("Access granted.\n");
    } else {
        printf("Access denied.\n");
    }

    return 0;
}

How It Works

Every character matches through the null terminator, so strcmp returns 0. For real passwords, avoid plain strcmp and use constant-time comparison to reduce timing attacks.

📈 Practical Patterns

Sorting, case rules, and command validation.

Example 3 — Sort Strings Alphabetically

Use strcmp as the comparison logic in a simple sort.

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

int main(void) {
    const char *names[] = { "Charlie", "Alice", "Bob" };
    int i, j;

    for (i = 0; i < 3; i++) {
        for (j = i + 1; j < 3; j++) {
            if (strcmp(names[i], names[j]) > 0) {
                const char *tmp = names[i];
                names[i] = names[j];
                names[j] = tmp;
            }
        }
    }

    for (i = 0; i < 3; i++) {
        printf("%s\n", names[i]);
    }

    return 0;
}

How It Works

When strcmp(names[i], names[j]) > 0, the first name sorts after the second, so pointers are swapped. Production code often uses qsort with strcmp as the comparator.

Example 4 — Case-Sensitive Comparison

strcmp treats uppercase and lowercase as different bytes.

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

int main(void) {
    const char *a = "OpenAI";
    const char *b = "openai";

    printf("strcmp: %d\n", strcmp(a, b));

    if (strcmp(a, b) == 0) {
        printf("Equal\n");
    } else {
        printf("Not equal (case differs at first letter).\n");
    }

    return 0;
}

How It Works

'O' (79) is less than 'o' (111), so the result is negative. For case-insensitive checks, use strcasecmp() (see our strcasecmp tutorial).

Example 5 — Match a Command String

Compare user input to a fixed command exactly.

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

int main(void) {
    const char *input = "exit";

    if (strcmp(input, "exit") == 0) {
        printf("Goodbye!\n");
    } else if (strcmp(input, "help") == 0) {
        printf("Commands: help, exit\n");
    } else {
        printf("Unknown command: %s\n", input);
    }

    return 0;
}

How It Works

CLI tools often branch on exact string matches. "Exit" or "EXIT" would fail here—that is when case-insensitive comparison helps.

🚀 Common Use Cases

  • Equality checks — verify tokens, usernames, or enum-like string values.
  • Sorting — order names, words, or paths with qsort.
  • Search structures — binary search on sorted string arrays.
  • Branching logic — dispatch on command names or mode strings.
  • Testing — assert expected output strings in unit tests.

🧠 How strcmp() Works

1

Read s1[i] and s2[i]

Start at index 0 and advance together.

Scan
2

Compare unsigned bytes

Stop at the first difference or at '\0' on both sides.

Compare
3

Return sign of difference

0 if all pairs matched and lengths are equal.

Result
=

int result

<0, 0, or >0 for less, equal, or greater.

📝 Notes

  • Case-sensitive—use strcasecmp when case should not matter.
  • Compares bytes as unsigned char—not locale-aware collation.
  • Only the sign of the return value is guaranteed for ordering.
  • Do not pass NULL pointers—behavior is undefined.
  • Shorter strings can sort before longer prefixes: "file" vs "file2" differ at the end.

⚡ Optimization

Standard library strcmp is heavily optimized. For most programs, use it directly rather than hand-rolling loops. When comparing the same prefix repeatedly, consider strncmp with a fixed limit or cache string lengths from strlen.

Conclusion

strcmp() is the standard C way to compare strings for equality and order. Remember == 0 for equal, respect case sensitivity, and use strncmp() when you need a bounded comparison.

Continue with strncmp() to compare at most n characters.

💡 Best Practices

✅ Do

  • Test equality with strcmp(a, b) == 0
  • Use the sign (<0, >0) for sorting comparisons
  • Include <string.h>
  • Use strncmp for prefix or length-limited checks
  • Prefer strcasecmp for user-facing case-insensitive text

❌ Don’t

  • Assume the return value is always -1, 0, or 1
  • Use strcmp on non-null-terminated data
  • Compare passwords with plain strcmp in security code
  • Write if (strcmp(a,b)) when you mean equal
  • Expect locale-aware sorting for accented characters

Key Takeaways

Knowledge Unlocked

Five things to remember about strcmp()

Use these points when comparing strings in C.

5
Core concepts
📝 02

Sign Matters

<0 or >0.

Return
🔢 03

Case Sensitive

a ≠ A.

Rules
📈 04

Sort & Search

qsort helper.

Use case
💬 05

vs strncmp

Limit n.

Compare

❓ Frequently Asked Questions

strcmp() compares two null-terminated C-strings lexicographically (byte by byte). It returns 0 if they are equal, a negative value if s1 is less than s2, or a positive value if s1 is greater than s2.
int strcmp(const char* s1, const char* s2); Include <string.h>. Both arguments must point to valid null-terminated strings.
Use strcmp(s1, s2) == 0. Do not compare the return value only to 1 or -1—the exact number is not standardized; only the sign matters for ordering.
Yes. "Hello" and "hello" are not equal. For case-insensitive comparison on POSIX use strcasecmp(); on Windows use _stricmp().
strcmp() compares until a difference or both strings end. strncmp(s1, s2, n) compares at most n bytes—useful for prefix checks and bounded comparisons.
Yes. Pass strcmp to qsort as the comparison function for an array of char* pointers. The sign of strcmp(a, b) tells qsort how to order the elements.
Did you know?

C compares string bytes as unsigned char values, so characters with high bit set sort after ASCII letters. For human language sorting (accents, locales), use strcoll() with an appropriate locale instead of plain strcmp.

Continue the String Functions Series

Master exact string comparison with strcmp(), then learn bounded compares with strncmp().

Next: strncmp() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful