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.
Fundamentals
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.
Foundation
📝 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.
< 0 — str1 is lexicographically less than str2.
> 0 — str1 is lexicographically greater than str2.
Header
#include <cstring>
Cheat Sheet
⚡ Quick Reference
str1
str2
strcmp 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
Hands-On
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;
}
📤 Output:
str1 is greater than str2.
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.
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;
}
📤 Output:
a is greater than b
How It Works
std::string::compare follows the same sign convention as strcmp. Operator == compares text content safely—unlike comparing raw char* pointers with ==.
Applications
🚀 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.
Important
📝 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().
Performance
⚡ 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.
Wrap Up
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.
Use strcmp for semantic version ordering without a dedicated parser
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about strcmp()
Use these points whenever you compare C-strings.
5
Core concepts
📊01
Lexicographic
Dictionary order.
Basics
🔢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.