C++ memcmp() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
<cstring>

Definition

In C++, memcmp() compares two blocks of n bytes.

Include <cstring>.

This guide shows the C library helper in a C++ .cpp program with std::cout. Prefer std::string for new text code; keep these APIs for C interop and interviews.

Syntax

Pass two pointers and a length.

C++
int c = std::memcmp(a, b, n);
CallWhat it does
std::memcmp(lhs, rhs, n)0 if equal; negative/positive like strcmp.

It does not stop at null bytes. For C-strings prefer strcmp when that is the model you want.

Library declarations
C++
int memcmp(const void* lhs, const void* rhs, size_t n);

Parameters

ParameterDescription
lhs, rhsBlocks to compare.
nBytes to compare.

Return Value

Return ValueDescription
intSign indicates ordering; 0 means equal for those n bytes.

C++ Examples

Example 1 — Basic memcmp()

Compare equal arrays.

C++
#include <cstring>
#include <iostream>

int main() {
    char a[] = "ab";
    char b[] = "ab";
    std::cout << std::memcmp(a, b, 2) << '\\n';
    return 0;
}

How It Works

  1. First two bytes match.
  2. memcmp returns 0.
  3. Meaning equal.

Example 2 — First Difference

Show ordering.

C++
#include <cstring>
#include <iostream>

int main() {
    char a[] = "ab";
    char b[] = "ac";
    std::cout << (std::memcmp(a, b, 2) < 0 ? "a<b" : "a>=b") << '\\n';
    return 0;
}

How It Works

  1. Second bytes differ: b vs c.
  2. a is less.
  3. We print a<b.

Example 3 — Compare Prefix

Equal prefixes compare equal.

C++
#include <cstring>
#include <iostream>

int main() {
    char a[] = "abc";
    char b[] = "abd";
    std::cout << std::memcmp(a, b, 2) << '\\n';
    return 0;
}

How It Works

  1. Only two bytes are compared.
  2. Those bytes match.
  3. Third characters are ignored.

Frequently Asked Questions

Compares n bytes of two memory regions.
No.
<cstring>.
0 equal; negative/positive for ordering.
strcmp/strncmp may be clearer when null-terminated text is the model.

Next: memcpy()

Keep going through the string functions. Copy bytes from source to destination (buffers must not overlap).

memcpy() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful