Difference between revisions of "cpp/string/byte/memcmp"
From cppreference.com
m (Update links.) |
m (link object representation) |
||
Line 21: | Line 21: | ||
===Notes=== | ===Notes=== | ||
− | This function reads object representations, not the object values, and is typically meaningful for trivially-copyable objects only. For example, {{tt|memcmp()}} between two objects of type {{lc|std::string}} or {{lc|std::vector}} will not compare their contents. | + | This function reads [[cpp/language/object|object representations]], not the object values, and is typically meaningful for trivially-copyable objects only. For example, {{tt|memcmp()}} between two objects of type {{lc|std::string}} or {{lc|std::vector}} will not compare their contents. |
===Example=== | ===Example=== |
Revision as of 07:30, 27 January 2014
Defined in header <cstring>
|
||
int memcmp( const void* lhs, const void* rhs, std::size_t count ); |
||
Reinterprets the objects pointed to by lhs
and rhs
as arrays of unsigned char and compares the first count
characters of these arrays. The comparison is done lexicographically.
Contents |
Parameters
lhs, rhs | - | pointers to the memory buffers to compare |
count | - | number of bytes to examine |
Return value
Negative value if the first differing byte (reinterpreted as unsigned char) in lhs
is less than the corresponding byte in rhs
.
0 if all count
bytes of lhs
and rhs
are equal.
Positive value if the first differing byte in lhs
is greater than the corresponding byte in rhs
.
Notes
This function reads object representations, not the object values, and is typically meaningful for trivially-copyable objects only. For example, memcmp()
between two objects of type std::string or std::vector will not compare their contents.
Example
Run this code
#include <iostream> #include <cstring> int main() { char a1[] = {'a', 'b', 'c'}; char a2[] = {'a', 'b', 'd'}; std::cout << "'abc' vs 'abd': " << std::memcmp(a1, a2, sizeof a1) << '\n' << "'abd' vs 'abc': " << std::memcmp(a2, a1, sizeof a1) << '\n' << "'abc' vs 'abc': " << std::memcmp(a1, a1, sizeof a1) << '\n'; }
Output:
'abc' vs 'abd': -1 'abd' vs 'abc': 1 'abc' vs 'abc': 0
See also
compares two strings (function) | |
compares a certain number of characters from two strings (function) | |
C documentation for memcmp
|