C++ strcmp() Function

Last Updated:

C++ strcmp()

The strcmp() function compares the characters of two strings.

The characters of the strings may be in lower case or upper case, this function discriminates between them.

Every character holds an ASCII value (an integer ranging from 0 to 127). For example, 'A' holds the ASCII value of 65 and 'a' holds the ASCII value of 97. So, in the comparison between two strings, their ASCII values are compared.

The strcmp() function starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered.

This function is defined in <cstring> header file.


C++ Compiler
#include <iostream> #include <cstring> using namespace std; int main() { const char str1[] = "ABCD"; const char str2[] = "abcd"; int res = strcmp(str1, str2); if(res == 0) cout << "str1 is equal to str2"; else if(res > 0) cout << "str1 is greater than str2"; else cout << "str1 is less than str2"; return 0; }


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

Parameter Values

str1 Required Specifies the string 1
str2 Required Specifies the string 2

Return Value

This function returns the numeric difference between the ASCII values of non-matching characters.

+ive If str1 is greater than str2
0 If str1 is equal to str2
-ive If str1 is less than str2

Share this Page

Meet the Author