C++ String strcmp() Function

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

What You’ll Learn

The strcmp() function from <cstring> compares two C-strings in lexicographic order (like dictionary order based on character codes). It returns an integer whose sign tells you whether the first string is less than, equal to, or greater than the second—essential for sorting, searching, and command matching.

01

Compare Strings

Two C-strings.

02

Returns int

Sign matters.

03

0 = Equal

Exact match.

04

< 0 / > 0

Less or greater.

05

Case-Sensitive

Exact letters.

06

vs strncmp()

Limited compare.

Definition and Usage

In C++, strcmp() walks both strings in parallel, comparing characters from first to last. When characters differ, it returns the difference of those character values (as an int). When one string ends before a difference is found, the shorter string is considered smaller.

You typically care about the sign of the result: zero means equal, negative means str1 sorts before str2, positive means str1 sorts after. The exact non-zero number is not standardized—do not rely on it being 1 or -1.

💡
Beginner Tip

Never compare C-strings with == on pointers—that checks whether they point to the same address, not whether the text matches. Use strcmp(a, b) == 0 for content equality.

📝 Syntax

The standard library declaration:

C++
int strcmp(const char* str1, const char* str2);

Parameters

  • str1 — first null-terminated C-string.
  • str2 — second null-terminated C-string.

Return Value

  • 0 — strings are equal.
  • < 0str1 is lexicographically less than str2.
  • > 0str1 is lexicographically greater than str2.

Header

#include <cstring>

⚡ Quick Reference

str1str2strcmp result
"apple""apple"0 (equal)
"apple""banana"< 0
"banana""apple"> 0
"Hello, World!""Hello, C++!"> 0 ('W' > 'C')
"cat""cats"< 0 (shorter ends first)
Equal?
strcmp(a, b) == 0

Same content

Less?
strcmp(a, b) < 0

a before b

Greater?
strcmp(a, b) > 0

a after b

std::string
a.compare(b)

Modern compare

Examples Gallery

Compile with g++ strcmp.cpp -std=c++17 -o strcmp. Each example interprets the return sign correctly—never assume the exact non-zero value.

📚 Getting Started

Compare two strings and interpret the result.

Example 1 — Basic strcmp() Usage

Compare "Hello, World!" with "Hello, C++!". They match until index 7: 'W' vs 'C'.

C++
#include <iostream>
#include <cstring>

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

    int result = std::strcmp(str1, str2);

    if (result == 0) {
        std::cout << "The strings are equal." << std::endl;
    } else if (result < 0) {
        std::cout << "str1 is less than str2." << std::endl;
    } else {
        std::cout << "str1 is greater than str2." << std::endl;
    }

    return 0;
}

How It Works

Characters match through "Hello, ". At the first difference, 'W' (ASCII 87) is greater than 'C' (67), so the result is positive.

Example 2 — Testing Equality

Use == 0 when you only need to know whether two strings contain the same text.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* password = "secret123";
    const char* input    = "secret123";

    if (std::strcmp(input, password) == 0) {
        std::cout << "Access granted." << std::endl;
    } else {
        std::cout << "Access denied." << std::endl;
    }

    return 0;
}

How It Works

Every character matches through the null terminator, so strcmp returns 0. Real password systems use hashing—this shows the equality pattern only.

📈 Practical Patterns

Ordering, commands, and modern C++ equivalents.

Example 3 — Lexicographic Ordering

See how dictionary order works with three fruit names.

C++
#include <iostream>
#include <cstring>

void report(const char* a, const char* b) {
    int cmp = std::strcmp(a, b);
    std::cout << '"' << a << "\" vs \"" << b << "\": ";
    if (cmp < 0) std::cout << "a comes first\n";
    else if (cmp > 0) std::cout << "b comes first\n";
    else std::cout << "same\n";
}

int main() {
    report("apple", "banana");
    report("banana", "apple");
    report("cherry", "cherry");
    return 0;
}

How It Works

strcmp compares character by character. 'a' < 'b', so "apple" sorts before "banana". Identical strings return 0.

Example 4 — Simple Command Handler

Match user input against known commands with equality checks.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* cmd = "help";

    if (std::strcmp(cmd, "quit") == 0) {
        std::cout << "Goodbye!" << std::endl;
    } else if (std::strcmp(cmd, "help") == 0) {
        std::cout << "Commands: help, quit" << std::endl;
    } else {
        std::cout << "Unknown command." << std::endl;
    }

    return 0;
}

How It Works

Each branch compares cmd to a literal C-string. Only exact matches trigger the branch—"Help" would not match "help" because comparison is case-sensitive.

Example 5 — Same Logic with std::string

C++ string objects provide compare() and == for content comparison.

C++
#include <iostream>
#include <string>

int main() {
    std::string a = "Hello, World!";
    std::string b = "Hello, C++!";

    if (a == b) {
        std::cout << "Equal" << std::endl;
    } else if (a.compare(b) < 0) {
        std::cout << "a is less than b" << std::endl;
    } else {
        std::cout << "a is greater than b" << std::endl;
    }

    return 0;
}

How It Works

std::string::compare follows the same sign convention as strcmp. Operator == compares text content safely—unlike comparing raw char* pointers with ==.

🚀 Common Use Cases

  • Sorting arrays of names — use strcmp as a comparator for qsort or custom sorts.
  • Command-line parsing — match argv tokens to known subcommands.
  • Configuration keys — compare option names read from files.
  • Version strings — rough lexicographic ordering (not always semver-correct).
  • C API interop — compare strings passed from libraries as const char*.

🧠 How strcmp() Works

1

Read both strings

Start at index 0 of str1 and str2.

Start
2

Compare characters

If bytes differ, return their difference as a signed int. If both reach '\\0', strings are equal.

Compare
3

Handle different lengths

If one string ends first, the shorter one is considered smaller.

Length
=

Return sign

Negative, zero, or positive tells you the ordering—use sign checks in your code.

📝 Notes

  • Comparison is case-sensitive"A" and "a" differ.
  • Both strings must be null-terminated; otherwise behavior is undefined.
  • Do not use == on char* pointers to compare text—use strcmp.
  • Only the sign of a non-zero result is portable; the exact value may vary.
  • For comparing only the first n characters, use strncmp().

⚡ Optimization

strcmp() is heavily optimized in standard libraries and is appropriate for most comparisons. If you compare the same long strings repeatedly, consider caching lengths or using std::string objects to avoid repeated scans. For locale-aware sorting (accents, language rules), use strcoll() instead.

Conclusion

strcmp() is the standard way to compare C-strings lexicographically. Remember: zero means equal, negative means the first string is smaller, positive means it is larger. Use sign checks, not magic numbers like 1 or -1.

Practice the examples, then explore strcoll() for locale-sensitive comparison and strncmp() for length-limited compares.

💡 Best Practices

✅ Do

  • Use strcmp(a, b) == 0 for equality
  • Check < 0 and > 0 for ordering
  • Ensure both strings are null-terminated
  • Prefer std::string and == in new C++ code
  • Use strcoll() when locale rules matter

❌ Don’t

  • Compare C-strings with pointer ==
  • Assume non-zero results are exactly 1 or -1
  • Expect case-insensitive matching by default
  • Pass non-null-terminated buffers to strcmp
  • Use strcmp for semantic version ordering without a dedicated parser

Key Takeaways

Knowledge Unlocked

Five things to remember about strcmp()

Use these points whenever you compare C-strings.

5
Core concepts
🔢 02

0 = Equal

Exact match.

Return
03

< 0 / > 0

Less or greater.

Sign
📝 04

Not ==

Compare content.

Safety
💬 05

Case-Sensitive

Exact letters.

Rule

❓ Frequently Asked Questions

strcmp() compares two null-terminated C-strings character by character using lexicographic (dictionary) order. It returns an int indicating whether the first string is less than, equal to, or greater than the second.
int strcmp(const char* str1, const char* str2); Include <cstring>. Both arguments must point to valid null-terminated strings.
Returns 0 if the strings are equal. Returns a value less than 0 if str1 comes before str2. Returns a value greater than 0 if str1 comes after str2. The exact non-zero value is implementation-defined—only the sign matters.
Yes: if (strcmp(a, b) == 0) means the strings match. Do not compare with > or < when you only need equality—the sign check is enough for ordering.
Yes. "Apple" and "apple" are different. For case-insensitive comparison on C-strings, use platform-specific helpers (e.g. _stricmp on Windows, strcasecmp on POSIX) or compare std::string with custom logic.
strcmp() compares until a mismatch or the end of either string. strncmp() compares at most n characters—useful when comparing fixed-width fields or limiting how much of a long string is examined.
Did you know?

Lexicographic order follows ASCII/Unicode code units, not always human sorting rules. Uppercase letters (A–Z) sort before lowercase (a–z) because their code values are smaller—so "Zebra" comes before "apple" in plain strcmp.

Continue the String Functions Series

Master C-string comparison with strcmp(), then learn locale rules with strcoll().

Next: strcoll() →

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