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.
Examples of memcmp()
Example 1
The following C++ program illustrates the use of memcmp() function when buf1 is greater than buf2.
C++
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char buff1[] = "Welcome to GeeksforGeeks" ;
char buff2[] = "Hello Geeks " ;
int a;
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;
}
|
OutputWelcome to GeeksforGeeks is greater than Hello Geeks
Example 2
The following C++ program illustrates the use of memcmp() function when buf1 is less than buf2.
C++
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
int comp = memcmp ( "GEEKSFORGEEKS" , "geeksforgeeks" , 6);
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" ;
}
}
|
OutputString 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++
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char buff1[] = "Welcome to GeeksforGeeks" ;
char buff2[] = "Welcome to GeeksforGeeks" ;
int a;
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;
}
|
OutputWelcome to GeeksforGeeks is the same as Welcome to GeeksforGeeks
This article is contributed by Shivani Ghughtyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.