Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is strcmp() in C++?
3.
Syntax of strcmp() in C++
3.1.
C++
4.
Parameters of strcmp() in C++
4.1.
C++
5.
Return Value of strcmp() in C++
5.1.
Negative Value
5.2.
Positive Value
5.3.
Zero
5.4.
C++
6.
strcmp() Prototype
6.1.
Return Type
6.2.
Function Name
6.3.
Parameters
6.4.
C++
7.
strcmp() Undefined Behavior
7.1.
Comparing Non-Null-Terminated Strings
7.2.
Passing NULL Pointers
7.3.
Modifying String Literals
7.4.
C++
8.
Implementation of strcmp() Function Using a User-Defined Function
8.1.
C++
9.
Frequently Asked Questions
9.1.
Is strcmp() case-sensitive?
9.2.
What happens if strcmp() is passed a null pointer?
9.3.
Can strcmp() be used to compare non-null-terminated strings?
10.
Conclusion
Last Updated: Jul 12, 2024
Easy

strcmp() in C++

Author Riya Singh
0 upvote

Introduction

In programming, comparing strings is a common but useful task that developers face almost very frequently. In C++, the strcmp() function is a built-in function that allows you to compare two strings & determine their lexicographic relationship. This function is part of the <cstring> library & is widely used for string comparison purposes. 

strcmp in C++

In this article, we will discuss the strcmp() function in detail, including its syntax, parameters, return values & implementation. 

What is strcmp() in C++?

strcmp() is a function in C++ that compares two null-terminated strings lexicographically. It is used to determine the relationship between two strings based on their character values. The function takes two strings as arguments & returns an integer value indicating the result of the comparison.

The strcmp() function compares the characters of the two strings one by one until it finds a difference or reaches the end of either string. It returns a negative value if the first string is lexicographically less than the second string, a positive value if the first string is lexicographically greater than the second string & zero if the two strings are equal.

Syntax of strcmp() in C++

The syntax of the strcmp() function is:

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


The strcmp() function takes two parameters, both of which are pointers to null-terminated strings (const char*). Here's a breakdown of the parameters

  • str1: A pointer to the first null-terminated string to be compared.
     
  • str2: A pointer to the second null-terminated string to be compared.
     

The function returns an integer value based on the comparison result:

  • If the return value is less than 0, it means that str1 is lexicographically less than str2.
     
  • If the return value is greater than 0, it means that str1 is lexicographically greater than str2.
     
  • If the return value is equal to 0, it means that str1 & str2 are equal.


Note: It's important to note that the strcmp() function is case-sensitive, meaning it treats uppercase & lowercase characters differently. If you want to perform a case-insensitive comparison, you can use the stricmp() function instead.

Here's an example that demonstrates the usage of strcmp() with the proper syntax:

  • C++

C++

#include <iostream>
#include <cstring>

using namespace std;

int main() {
const char *str1 = "apple";
const char *str2 = "banana";

int result = strcmp(str1, str2);

if (result < 0) {
cout << str1 << " is less than " << str2 << endl;
} else if (result > 0) {
cout << str1 << " is greater than " << str2 << endl;
} else {
cout << str1 << " is equal to " << str2 << endl;
}

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

apple is less than banana


In this example, we compare the strings "apple" & "banana" using strcmp(). Since "apple" is lexicographically less than "banana", the function returns a negative value, & the output will be "apple is less than banana".

Parameters of strcmp() in C++

The strcmp() function in C++ takes two parameters, both of which are pointers to null-terminated strings. Let's discuss these parameters in more detail:

const char *str1:


This parameter represents a pointer to the first null-terminated string to be compared.

The const keyword indicates that the string pointed to by str1 should not be modified within the strcmp() function.

The string is expected to be null-terminated, meaning it should have a null character ('\0') at the end to mark the termination of the string.

const char *str2:


This parameter represents a pointer to the second null-terminated string to be compared.

Similar to str1, the const keyword indicates that the string pointed to by str2 should not be modified within the strcmp() function.

The string is also expected to be null-terminated.


It's important to note that the strcmp() function expects the strings to be null-terminated. If the strings are not properly null-terminated, the function may read beyond the end of the strings, leading to undefined behavior.

Let’s see an example that  the usage of strcmp() with the correct parameter types:

  • C++

C++

#include <iostream>

#include <cstring>

using namespace std;

int main() {

   const char *str1 = "Hello";

   const char *str2 = "Hello";   

   int result = strcmp(str1, str2);

   if (result == 0) {

       cout << "The strings are equal." << endl;

   } else {

       cout << "The strings are not equal." << endl;

   }   

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code


Output

The strings are equal.


In this example, we pass two identical strings "Hello" as the parameters to strcmp(). Since the strings are equal, the function returns 0, & the output will be "The strings are equal."

It's important to remember  that strcmp() compares the strings character by character based on their ASCII values. It starts comparing from the first character of each string & continues until it finds a mismatch or reaches the end of either string.

Return Value of strcmp() in C++

The strcmp() function in C++ returns an integer value that indicates the relationship between the two strings being compared. The return value can be one of three possibilities:

Negative Value

  • If the return value is less than 0, it means that the first string (str1) is lexicographically less than the second string (str2).
     
  • In other words, str1 comes before str2 in dictionary order.

Positive Value

  • If the return value is greater than 0, it means that the first string (str1) is lexicographically greater than the second string (str2).
     
  • In other words, str1 comes after str2 in dictionary order.

Zero

  • If the return value is equal to 0, it means that the two strings (str1 and str2) are lexicographically equal.
     
  • In other words, str1 and str2 have the same characters in the same order


The specific value returned by strcmp() depends on the implementation of the function. However, the sign of the return value (negative, positive, or zero) consistently indicates the lexicographic relationship between the strings.

Here's an example that demonstrates the possible return values of strcmp():

  • C++

C++

#include <iostream>

#include <cstring>

using namespace std;

int main() {

   const char *str1 = "apple";

   const char *str2 = "banana";

   const char *str3 = "apple";   

   int result1 = strcmp(str1, str2);

   int result2 = strcmp(str2, str1);

   int result3 = strcmp(str1, str3);   

   cout << "strcmp(\"apple\", \"banana\") returns: " << result1 << endl;

   cout << "strcmp(\"banana\", \"apple\") returns: " << result2 << endl;

   cout << "strcmp(\"apple\", \"apple\") returns: " << result3 << endl;

  

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code


Output

strcmp("apple", "banana") returns: -1
strcmp("banana", "apple") returns: 1
strcmp("apple", "apple") returns: 0


In this example, we compare different combinations of strings using strcmp(). The return values indicate the lexicographic relationship between the strings:

  • strcmp("apple", "banana") returns a negative value (-1) because "apple" is lexicographically less than "banana".
     
  • strcmp("banana", "apple") returns a positive value (1) because "banana" is lexicographically greater than "apple".
     
  • strcmp("apple", "apple") returns zero (0) because the two strings are equal.

strcmp() Prototype

The prototype of the strcmp() function in C++ is :

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


Let's break down the components of the prototype:

Return Type

  • The strcmp() function returns an integer value (int).
     
  • The return value indicates the lexicographic relationship between the two strings being compared.

Function Name

  • The name of the function is "strcmp".
     
  • It stands for "string compare".

Parameters

  • The strcmp() function takes two parameters, both of which are pointers to null-terminated strings.
     
  • The first parameter, str1, is a pointer to the first string to be compared.
     
  • The second parameter, str2, is a pointer to the second string to be compared.
     
  • Both parameters are declared as const char *, which means they are pointers to constant characters.


The prototype of strcmp() is typically declared in the <cstring> header file. To use the strcmp() function in your C++ program, you need to include this header file.

For example : 

  • C++

C++

#include <iostream>
#include <cstring>

using namespace std;

int main() {
const char *str1 = "Hello";
const char *str2 = "World";

int result = strcmp(str1, str2);

if (result < 0) {
cout << str1 << " is less than " << str2 << endl;
} else if (result > 0) {
cout << str1 << " is greater than " << str2 << endl;
} else {
cout << str1 << " is equal to " << str2 << endl;
}

return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output:

Hello is less than World


In this example, we include the <cstring> header file to access the strcmp() function. We declare two const char pointers, str1 and str2, which point to the strings "Hello" and "World", respectively.

We then call the strcmp() function, passing str1 and str2 as arguments. The return value of strcmp() is stored in the result variable.

Based on the value of result, we use conditional statements to determine the relationship between the strings and print the appropriate message.

strcmp() Undefined Behavior

When using the strcmp() function in C++, it's important to be aware of situations that can lead to undefined behavior. Undefined behavior occurs when the program's behavior is not well-defined by the C++ standard, and the outcome can be unpredictable or erroneous.

Here are a few scenarios where using strcmp() can result in undefined behavior:

Comparing Non-Null-Terminated Strings

  • The strcmp() function expects both input strings to be null-terminated.
     
  • If either of the strings is not properly null-terminated, strcmp() may read beyond the end of the string, leading to undefined behavior.
     
  • It's crucial to ensure that the strings being compared are null-terminated to avoid this issue.

Passing NULL Pointers

  • If either of the pointers passed to strcmp() is a null pointer (NULL), the behavior is undefined.
     
  • Dereferencing a null pointer can lead to program crashes or unexpected results.
     
  • Always check for null pointers before passing them to strcmp() to prevent undefined behavior.

Modifying String Literals

  • String literals in C++ are typically stored in read-only memory.
     
  • Attempting to modify a string literal directly can lead to undefined behavior.
     
  • If you need to modify a string, use a character array or a mutable string type like std::string.
     

Here's an example that demonstrates undefined behavior with strcmp():

#include <iostream>
#include <cstring>
using namespace std;
int main() {
    const char *str1 = "Hello";
    char str2[5] = "World";  // Not null-terminated
    
    int result = strcmp(str1, str2);  // Undefined behavior
    
    cout << "Comparison result: " << result << endl;
    
    return 0;
}


In this example, str2 is declared as a character array with a size of 5, but the string "World" requires 6 characters (including the null terminator). As a result, str2 is not properly null-terminated.

When strcmp() is called with str1 and str2, it reads beyond the end of str2 since it lacks a null terminator. This leads to undefined behavior, and the output of the program is unpredictable.

To avoid undefined behavior, make sure that the strings being compared are properly null-terminated and that null pointers are checked before being passed to strcmp().

Here's the corrected version of the example:

  • C++

C++

#include <iostream>

#include <cstring>

using namespace std;

int main() {

   const char *str1 = "Hello";

   char str2[6] = "World";  // Properly null-terminated   

   int result = strcmp(str1, str2);   

   cout << "Comparison result: " << result << endl;  

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code


Output

Comparison result: -15


In this case, str2 is declared with a size of 6, allowing space for the null terminator. The program now has well-defined behavior, and the output will be consistent.

Implementation of strcmp() Function Using a User-Defined Function

While the strcmp() function is readily available in the C++ standard library, it can be helpful to understand how it can be implemented using a user-defined function. By creating our own version of strcmp(), we can gain a deeper understanding of the string comparison process.

Here's an example implementation of the strcmp() function using a user-defined function:

  • C++

C++

#include <iostream>

using namespace std;

int myStrcmp(const char *str1, const char *str2) {

   while (*str1 && (*str1 == *str2)) {

       str1++;

       str2++;

   }

   return *(const unsigned char*)str1 - *(const unsigned char*)str2;

}

int main() {

   const char *str1 = "Hello";

   const char *str2 = "Hello";

   const char *str3 = "World";  

   int result1 = myStrcmp(str1, str2);

   int result2 = myStrcmp(str1, str3);

   int result3 = myStrcmp(str3, str1);   

   cout << "myStrcmp(\"Hello\", \"Hello\") returns: " << result1 << endl;

   cout << "myStrcmp(\"Hello\", \"World\") returns: " << result2 << endl;

   cout << "myStrcmp(\"World\", \"Hello\") returns: " << result3 << endl;   

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

In this example, we define a user-defined function called myStrcmp() that takes two const char pointers (str1 and str2) as parameters. The function compares the characters of the two strings until either a mismatch is found or the end of both strings is reached.

The comparison is done using a while loop that iterates until either str1 reaches the null terminator or a mismatch is found between the characters of str1 and str2. The loop increments both str1 and str2 pointers to move to the next characters in the strings.

After the loop ends, the function returns the difference between the characters at the current positions of str1 and str2. The characters are cast to const unsigned char* to ensure proper comparison of the character values.

In the main() function, we demonstrate the usage of the myStrcmp() function by comparing different combinations of strings. The results are printed to the console.

Output:

myStrcmp("Hello", "Hello") returns: 0
myStrcmp("Hello", "World") returns: -15
myStrcmp("World", "Hello") returns: 15


As expected, comparing "Hello" with itself returns 0, indicating that the strings are equal. Comparing "Hello" with "World" returns a negative value (-15), indicating that "Hello" is lexicographically less than "World". Comparing "World" with "Hello" returns a positive value (15), indicating that "World" is lexicographically greater than "Hello".

Frequently Asked Questions

Is strcmp() case-sensitive?

Yes, strcmp() is case-sensitive. It treats uppercase & lowercase characters differently.

What happens if strcmp() is passed a null pointer?

Passing a null pointer to strcmp() leads to undefined behavior & should be avoided.

Can strcmp() be used to compare non-null-terminated strings?

No, strcmp() expects both strings to be null-terminated. Comparing non-null-terminated strings results in undefined behavior.

Conclusion

In this article, we talked about the strcmp() function in C++, which is used to compare two null-terminated strings lexicographically. We covered its syntax, parameters, return values & implementation. We also discussed potential undefined behavior scenarios & provided an example of implementing strcmp() using a user-defined function. 

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass