Examples of memcmp()
Example 1
The following C++ program illustrates the use of memcmp() function when buf1 is greater than buf2.
C++
Output
Welcome to w3wiki is greater than Hello Geeks
Example 2
The following C++ program illustrates the use of memcmp() function when buf1 is less than buf2.
C++
// CPP program to illustrate std::memcmp() #include <cstring> #include <iostream> using namespace std; int main() { // comparing two strings directly int comp = memcmp ( "w3wiki" , "w3wiki" , 6); // result output if (comp == 0) { cout << "both are equal" ; } else if (comp < 0) { cout << "String 1 is less than String 2" ; } else { cout << "String 1 is greater than String 2" ; } } |
Output
String 1 is less than String 2
Example 3
The following C++ program illustrates the use of memcmp() function when buf1 is equal to buf2.
C++
// CPP program to illustrate std::memcmp() #include <cstring> #include <iostream> using namespace std; int main() { // two buffers char buff1[] = "Welcome to w3wiki" ; char buff2[] = "Welcome to w3wiki" ; int a; // defining count using sizeof operator a = memcmp (buff1, buff2, sizeof (buff1)); if (a > 0) cout << buff1 << " is greater than " << buff2; else if (a < 0) cout << buff1 << "is less than " << buff2; else cout << buff1 << " is the same as " << buff2; return 0; } |
Output
Welcome to w3wiki is the same as Welcome to w3wiki
std::memcmp() in C++
memcmp() function compares the first count bytes ( given number of characters ) of the memory pointed to by buf1 and buf2. memcmp() is a Standard Library function defined in <string.h> header file in C++.
Syntax
int memcmp(const void *buf1, const void *buf2, size_t count);
Parameters
- buf1: Pointer to block of a memory buffer that will be compared with a second memory buffer.
- buf2: Pointer to the second block of memory buffer.
- count: Maximum numbers of bytes to compare.
Return Values
- It returns 0 when buf1 is equal to buf2.
- It returns an integer value less than zero when the first different byte in both memory buffers is less in buf1 than buf2.
- It returns an integer value greater than zero when the first different byte that is different in both memory buffers is greater in buf1 than buf2.
Note: The memcmp function does not look for ‘\0’ NULL character in the string. It will keep comparing the bytes till the specified count.
Contact Us