From the man page:
The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.
Example code in C (prints -15
on my machine, swapping test1 and test2 inverts the value):
#include <stdio.h>
#include <string.h>
int main() {
char* test1 = "hello";
char* test2 = "world";
printf("%d\n", strcmp(test1, test2));
}
I found this code (taken from this question) that relies on the values of strcmp being something other than -1, 0 and 1 (it uses the return value in qsort
). To me, this is terrible style and depends on undocumented features.
I guess I have two, related questions:
Edit:
After leaving my computer for 5 minutes, I realized that there is in fact no error with the code in question. I struck out the parts that I figured out before reading the comments/answers, but I left them there to keep the comments relevant. I think this is still an interesting question and may cause hiccups for programmers used to other languages that always return -1, 0 or 1 (e.g. Python seems to do this, but it's not documented that way).
FWIW, I think that relying on something other than the documented behavior is bad style.
Is there something in the C standard that defines what the return values are besides less than, greater than, or equal to zero?
No. The tightest constraint is that it should be zero, less than zero or more than zero, as specified in the documentation of this particular function.
If not, what does the standard implementation do?
There's no such thing as "the standard implementation". Even if there was, it would probably just
return zero, less than zero or more than zero;
:-)
Is the return value consistent across the Linux, Windows and the BSDs?
I can confirm that it's consistent across Linux and OS X as of 10.7.4 (specifically, it's -1, 0 or +1). I have no idea about Windows, but I bet Microsoft guys use -2 and +3 just to break code :P
Also, let me also point out that you have completely misunderstood what the code does.
I found this code (taken from this question) that relies on the values of strcmp being something other than -1, 0 and 1 (it uses the return value in qsort). To me, this is terrible style and depends on undocumented features.
No, it actually doesn't. The C standard library is designed with consistency and ease of use in mind. That is, what qsort()
requires is that its comparator function returns a negative or a positive number or zero - exactly what strcmp()
is guaranteed to do. So this is not "terrible style", it's perfectly standards-conformant code which does not depend upon undocumented features.