For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
Why does strcmp("hello", "Hello") return a non-zero value in C?
Because the strcmp function checks every character—case and all.
The strcmp in C function is used to compare two strings character by character. It returns 0 if both strings are equal, a positive value if the first string is greater, and a negative value if it’s smaller. This makes it essential in sorting strings, validating input, and implementing search operations.
In this tutorial, you’ll learn how strcmp in C works, how to interpret its return values, and when to use it in real programs. We’ll walk through simple examples to show what happens when strings match, differ by case, or have different lengths.
By the end, you’ll have a clear understanding of how to compare strings effectively in C. Want to strengthen your command of C programming and core concepts? Explore our Software Engineering Courses to build practical skills that matter.
strcmp in C programming is a standard library function that compares two strings. It is done character by character, and the function determines whether the strings are equal or which one is lexicographically greater or smaller.
A real-world example of using strcmp() for string validation would be comparing a user's password input against a stored password.
For instance, when a user logs into a system, strcmp() can be used to compare the entered password with the one stored in the system’s database.
The general syntax of the strcmp() function is as follows:
int strcmp(const char *str1, const char *str2);
Let’s break it down:
You’ve done great mastering the fundamentals of C! Why not take the next step and dive deeper into today’s most sought-after technologies? Here are three impactful options:
The strcmp() function is declared in the <string.h> header file, which is part of the C Standard Library. This header contains the necessary function declarations for string manipulation functions, including strcmp().
If you forget to include <string.h>, the compiler won’t recognize strcmp(), leading to a compilation error.
The program will likely generate an error message like "undefined reference to 'strcmp'," which means the compiler doesn't know what strcmp() is.
By including <string.h>, you gain access to a variety of functions for handling and manipulating strings, including strcmp(), which is specifically used to compare two null-terminated strings in C programming.
Let’s break down what the return value means:
Also Read: String Functions in C
Next, let's look at how to use strcmp in C programming for practical tasks like string comparison and sorting.
Here's how you can use it to compare two user-input strings for equality.
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100]; // Arrays to store user input strings
// Getting user input
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin); // Input first string
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin); // Input second string
// Remove newline characters that fgets() might add
str1[strcspn(str1, "\n")] = '\0';
str2[strcspn(str2, "\n")] = '\0';
// Comparing the strings using strcmp()
if (strcmp(str1, str2) == 0) { // Check if the strings are equal
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
Output:
Enter first string: hello
Enter second string: hello
The strings are equal.
Enter first string: hello
Enter second string: world
The strings are not equal.
Explanation:
Let’s dive into how strcmp() works under the hood.
Here's the step-by-step breakdown of how it works:
Stopping Condition:
Using strcmp() in C programming provides a reliable and precise way to compare strings, ensuring content is compared character by character, unlike relational operators such as ==, <, or >, which compare memory addresses or only the first character.
Let’s look at the details:
Key Takeaways:
Also Read: How to Implement Selection Sort in C?
Now that you know how strcmp() works, let's explore some examples.
These examples will help you understand how to handle case sensitivity, and even use strcmp() for sorting strings lexicographically.
Let’s dive into it!
The strcmp() function is case-sensitive, distinguishing between uppercase and lowercase characters.
In this example, let's compare "apple" and "Apple" to see how strcmp() behaves when case differences exist.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "Apple";
// Comparing the strings using strcmp()
int result = strcmp(str1, str2); // Case-sensitive comparison
if (result == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal. Result: %d\n", result); // Non-zero result
}
return 0;
}
Output:
The strings are not equal. Result: 32
Explanation:
Now, let's use strcmp() to sort an array of strings lexicographically (alphabetically). You’ll look at how it can be integrated into a sorting algorithm like Bubble Sort to sort an array of strings in ascending order.
#include <stdio.h>
#include <string.h>
void bubbleSort(char arr[][100], int n) {
char temp[100];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (strcmp(arr[j], arr[j + 1]) > 0) { // Compare two strings
// Swap strings if they are out of order
strcpy(temp, arr[j]);
strcpy(arr[j], arr[j + 1]);
strcpy(arr[j + 1], temp);
}
}
}
}
int main() {
char fruits[][100] = {"Banana", "Apple", "Cherry", "Mango", "Pineapple"};
int n = sizeof(fruits) / sizeof(fruits[0]); // Number of strings in the array
printf("Before sorting:\n");
for (int i = 0; i < n; i++) {
printf("%s\n", fruits[i]);
}
// Sorting the array of strings
bubbleSort(fruits, n);
printf("\nAfter sorting:\n");
for (int i = 0; i < n; i++) {
printf("%s\n", fruits[i]);
}
return 0;
}
Output:
Before sorting:
Banana
Apple
Cherry
Mango
Pineapple
After sorting:
Apple
Banana
Cherry
Mango
Pineapple
Explanation:
Key Takeaways:
Let’s move on to some common errors you should be aware of.
When using strcmp in C programming, there are a few common errors and misunderstandings that can cause issues, especially for beginners.
Let’s walk through some of them:
In C programming, strings must be null-terminated, meaning that the last character of the string must be the special character '\0' (null character).
If a string is not null-terminated, strcmp() will continue comparing characters beyond the end of the string, leading to undefined behavior or memory access errors.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "hello "; // This string is not properly null-terminated
if (strcmp(str1, str2) == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
Output:
The strings are not equal.
Explanation:
A common mistake is confusing strcmp() with a pointer comparison using ==. In C, the == operator compares the addresses of the two strings (the memory locations where they are stored), not their content.
This can lead to unexpected results when comparing strings.
#include <stdio.h>
int main() {
char str1[] = "hello";
char str2[] = "hello"; // Both strings have the same content, but different addresses
if (str1 == str2) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
Output:
The strings are not equal.
Explanation:
Avoiding these common pitfalls, you can effectively use strcmp in your C programming projects.
1. What is the purpose of strcmp() in C?
a) Copy one string to another
b) Compare two strings
c) Reverse a string
d) Concatenate strings
2. Which header file is required to use strcmp()?
a) stdio.h
b) stdlib.h
c) string.h
d) math.h
3. What is the return type of strcmp()?
a) char
b) int
c) void
d) bool
4. What does strcmp("abc", "abc") return?
a) 1
b) -1
c) 0
d) NULL
5. What is the return value of strcmp("abc", "abd")?
a) 0
b) Positive value
c) Negative value
d) Error
6. What does a negative return value from strcmp(a, b) indicate?
a) a is greater than b
b) a is equal to b
c) a is less than b
d) a is NULL
7. Which of these comparisons is case-sensitive in C?
a) str1 == str2
b) strcmp(str1, str2)
c) str1 != str2
d) str1 equals str2
8. What happens if one of the strings in strcmp() is NULL?
a) Returns 0
b) Always returns -1
c) Causes undefined behavior or segmentation fault
d) Returns true
9. A student writes if(strcmp(str1, str2)) but it behaves unexpectedly when strings match. Why?
a) strcmp returns a pointer
b) strcmp returns 0 when strings match
c) Condition is incorrect
d) Both b and c
10. You are sorting an array of strings alphabetically. Which function should be used for comparison in qsort()?
a) strcmp()
b) strlen()
c) strcpy()
d) scanf()
11. Your interviewer asks how strcmp() works internally. What's the best answer?
a) It compares string lengths
b) It compares characters one by one using ASCII values
c) It converts strings to integers
d) It only checks the first character
upGrad offers comprehensive courses to deepen your understanding of C programming, covering key topics such as string manipulation, algorithms, and memory management. By mastering functions like strcmp, you'll be equipped with the knowledge to tackle more advanced programming challenges, like building efficient data structures and optimizing code.
Explore upGrad’s specialized courses to level up your C programming skills:
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Array in C: Introduction, Declaration, Initialisation and More
Exploring Array of Pointers in C: A Beginner's Guide
What is C Function Call Stack: A Complete Tutorial
Binary Search in C
Constant Pointer in C: The Fundamentals and Best Practices
Dangling Pointer in C: Causes, Risks, and Prevention Techniques
Find Out About Data Structures in C and How to Use Them?
The strcmp in C programming function compares string content character by character, while == compares memory addresses, leading to incorrect results for string comparison.
strcmp in C programming is case-sensitive. It considers "apple" and "Apple" different due to ASCII value differences between lowercase and uppercase characters.
Yes, you can use strcmp in C with example in sorting algorithms, such as Bubble Sort or Quick Sort, to compare and arrange strings in lexicographical order.
strcmp() compares each character. If the strings differ in length, it stops comparing when the null character (\0) is encountered in the shorter string, returning the difference in ASCII values.
strcmp() compares strings character by character. It stops if a mismatch occurs or when the null character is reached, returning the difference in ASCII values.
strcmp() is efficient for comparing string content, especially for strcmp in C programming, as it stops once a mismatch is found, avoiding unnecessary comparisons.
strcmp() is case-sensitive by default. For case-insensitive comparisons, you can either convert both strings to lowercase or uppercase before comparing, or use stricmp() in some compilers.
Null-termination is crucial because strcmp in C programming relies on the null character (\0) to determine the end of the string. Without it, the function may read beyond the string's boundary, leading to undefined behavior.
When two strings are identical, strcmp() returns 0, indicating they are equal, as shown in strcmp in C with example.
strcmp() is useful in validating user inputs. For example, you can compare user input with expected strings to check if the input matches the required value, ensuring correct input.
No, strcmp() is specifically designed to compare strings (character arrays). If you need to compare different data types, you should convert them to strings before using strcmp in C programming.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Previous
Next
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.