How to Use strcmp in C: Syntax, Example, and Tips
In C, use
strcmp to compare two strings by passing their pointers to the function. It returns 0 if the strings are equal, a negative value if the first string is less, and a positive value if the first string is greater.Syntax
The strcmp function compares two strings character by character.
- int strcmp(const char *str1, const char *str2);
str1andstr2are pointers to the strings to compare.- Returns 0 if both strings are equal.
- Returns a negative value if
str1is less thanstr2. - Returns a positive value if
str1is greater thanstr2.
c
int strcmp(const char *str1, const char *str2);
Example
This example shows how to compare two strings using strcmp and print the result.
c
#include <stdio.h> #include <string.h> int main() { const char *a = "apple"; const char *b = "banana"; int result = strcmp(a, b); if (result == 0) { printf("Strings are equal.\n"); } else if (result < 0) { printf("'%s' is less than '%s'.\n", a, b); } else { printf("'%s' is greater than '%s'.\n", a, b); } return 0; }
Output
'apple' is less than 'banana'.
Common Pitfalls
Common mistakes when using strcmp include:
- Using
==to compare strings instead ofstrcmp. This compares pointers, not content. - Not checking the return value properly (only checking for equality, ignoring less or greater).
- Passing uninitialized or NULL pointers to
strcmp, which causes undefined behavior.
c
#include <stdio.h> #include <string.h> int main() { const char *str1 = "hello"; const char *str2 = "hello"; // Wrong: compares addresses, not string content if (str1 == str2) { printf("Wrong: Strings are equal.\n"); } else { printf("Wrong: Strings are not equal.\n"); } // Right: use strcmp to compare content if (strcmp(str1, str2) == 0) { printf("Right: Strings are equal.\n"); } else { printf("Right: Strings are not equal.\n"); } return 0; }
Output
Wrong: Strings are not equal.
Right: Strings are equal.
Quick Reference
| Return Value | Meaning |
|---|---|
| 0 | Strings are equal |
| < 0 | First string is less than second string |
| > 0 | First string is greater than second string |
Key Takeaways
Use strcmp to compare string contents, not the == operator.
strcmp returns 0 if strings match exactly.
Check if strcmp result is less than or greater than zero to know order.
Never pass NULL pointers to strcmp to avoid crashes.
Always include to use strcmp.