In C++, strcmp() compares two C-strings, one character at a time. It tells you whether they are the same, or which one comes first. Letter case matters: "Cat" and "cat" are not the same.
Both strings are required. The result is 0 when they match, less than 0 when the first comes first, and greater than 0 when the first comes after. Do not use == on two char* values. That compares addresses, not the letters. Include <cstring>.
Syntax
Compare the two strings, then test the number that comes back.
C++
strcmp("cat", "car");
Call
What it does
strcmp("cat", "car")
Compares cat with car. The result is not 0, because the words differ.
Library declarations
C++
int strcmp(const char* lhs, const char* rhs);
Parameters
Parameter
Description
first
Required. The first C-string.
second
Required. The second C-string.
Return Value
Return Value
Description
0
The two strings are the same.
Less than 0
The first string comes before the second.
Greater than 0
The first string comes after the second.
C++ Examples
Example 1 — Test Equality
Check whether two C-strings match.
C++
#include <iostream>
#include <cstring>
int main() {
const char* a = "C++";
const char* b = "C++";
const char* c = "Java";
if (strcmp(a, b) == 0) {
std::cout << "a and b are equal\n";
}
if (strcmp(a, c) != 0) {
std::cout << "a and c are different\n";
}
return 0;
}
Output
a and b are equal
a and c are different
How It Works
strcmp(a, b) == 0 means every character matches.
!= 0 means the strings differ.
Case and spelling both matter.
Example 2 — Which Comes First?
Use the sign of the result for dictionary order.
C++
#include <iostream>
#include <cstring>
int main() {
const char* left = "Apple";
const char* right = "Banana";
int result = strcmp(left, right);
if (result < 0) {
std::cout << left << " comes before " << right << '\n';
} else if (result > 0) {
std::cout << left << " comes after " << right << '\n';
} else {
std::cout << "Equal\n";
}
return 0;
}
Output
Apple comes before Banana
How It Works
Characters are compared until they differ.
'A' is less than 'B', so result is negative.
Useful for sorting C-string lists.
Example 3 — Clearer Style with std::string
Same equality check without strcmp.
C++
#include <iostream>
#include <string>
int main() {
std::string a = "C++";
std::string b = "C++";
if (a == b) {
std::cout << "Equal\n";
}
return 0;
}
Output
equal
How It Works
std::string overloads == for text content.
No need to remember return codes for a simple match.
Learn strcmp for C APIs; prefer == in new C++.
Frequently Asked Questions
strcmp() compares two C-strings and tells you if they are the same or which one comes first.
Two C-strings. The first is compared with the second.
0 when the strings are the same, a negative number when the first comes first, and a positive number when the first comes after.
Check that strcmp(a, b) == 0. Do not use a == b, because that compares pointers.
Yes. Uppercase and lowercase letters are different.