C++ memcmp()

The memcmp() function in C++ compares a specified number of characters of two pointer objects

memcmp() prototype

int memcmp( const void* lhs, const void* rhs, size_t count );

The memcmp() function takes three arguments: lhs, rhs and count. This function first interprets the objects pointed to by lhs and rhs as arrays of unsigned char. Then it compares the first count characters of lhs and rhs lexicographically.

It is defined in <cstring> header file.

memcmp() Parameters

  • lhs and rhs: Pointer to the memory objects to compare.
  • count: Maximum numbers of bytes to compare.

memcmp() Return value

The memcmp() function returns a:

  • positive value if the first differing byte in lhs is greater than the corresponding byte in rhs.
  • negative value if the first differing byte in lhs is less than the corresponding byte in rhs.
  • 0​ if the first count bytes of lhs and rhs are equal.

Example: How memcmp() function works

#include <cstring>
#include <iostream>

using namespace std;

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

int main()
{
    char lhs[] = "Hello World!";
    char rhs[] = "Hello Earth!";
    int result;

    result = memcmp(lhs, rhs, 5);
    display(lhs, rhs, result, 5);
    
    result = memcmp(lhs, rhs, 7);
    display(lhs, rhs, result, 7);
    return 0;
}

When you run the program, the output will be:

First 5 characters of Hello World! and Hello Earth! are same
Hello Earth! precedes Hello World!
Did you find this article helpful?