If I pass memcmp
the equal pointers for its first and second argument,
I suspected that it might just return 0 without checking the elements -- since if the same pointer is passed the elements must be zero.
It seems like to me it is good optimization to check for pointer equality and exit early.
I checked the glibc and Free BSD LibC implementations and neither seem to be making this optimization.
So I checked the standard (below): The Open Standards draft version of C99 says nothing one way or the other:
7.21.4.1 The memcmp function Synopsis
#include <string.h> int memcmp(const void *s1, const void *s2, size_t n);
Description
The memcmp function compares the first n characters of the object pointed to by s1 to the first n characters of the object pointed to by s2.
Returns
The memcmp function returns an inte ger greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2
As far as I can tell it doesn't forbid such an "trick", since one would still get the same returned values. It is really is an implementation detail, AFAICT.
Clearly the people writing these libraries have put much more thought into this than I have, so there is probably a good reason for not doing this. What is it?