Join our newsletter for the latest updates.

C++ strcmp()

The strcmp() function in C++ compares two null terminating string. The comparison is done lexicographically.

strcmp() prototype

int strcmp( const char* lhs, const char* rhs );

The strcmp() function takes two arguments: lhs and rhs. It compares the contents of lhs and rhs lexicographically. The sign of the result is the sign of difference between the first pairs of characters that differ in lhs and rhs.

The behaviour of strcmp() is undefined if either of lhs or rhs do not point to null terminated strings.

It is defined in <cstring> header file.

strcmp() Parameters

lhs and rhs: Pointer to the null terminated strings to compare.

strcmp() Return value

The strcmp() function returns a:

  • positive value if the first differing character in lhs is greater than the corresponding character in rhs.
  • negative value if the first differing character in lhs is less than the corresponding character in rhs.
  • 0‚Äč if hs and rhs are equal.

Example: How strcmp() function works

#include <cstring>
#include <iostream>

using namespace std;

void display(char *lhs, char *rhs, int result)
    if(result > 0)
        cout << rhs << " precedes " << lhs << endl;
    else if (result < 0)
        cout << lhs << " precedes " << rhs << endl;
        cout << lhs << " and " << rhs << " are same" << endl;

int main()
    char lhs[] = "Armstrong";
    char rhs[] = "Army";
    int result;

    result = strcmp(lhs,rhs);

    result = strcmp(lhs,lhs);

    return 0;

When you run the program, the output will be:

Armstrong precedes Army
Armstrong and Armstrong are same