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:
- Is there something in the C standard that defines what the return values are besides less than, greater than, or equal to zero? If not, what does the standard implementation do?
- Is the return value consistent across the Linux, Windows and the BSDs?
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.
strcmp's return value other than its sign. - Fred Foostrcmp. On the contrary, the code does not rely on any specific return values, which is actually very good style. So, what exactly do you mean? - AnTqsort()comparator are that it returns "an integer less than, equal to, or greater than zero" which is exactly whatstrcmp()does. There's no abuse of any sort going on. - Hasturkunw) from ASCII char 104 (h). So104 - 119 = -15. I'd suspect that if you changetest1tojelloyou'll get a result of-16and so on. The man page you quoted specifically says "less than"; it doesn't say anything about "-1". IOW, a value less than zero would be any negative number except zero, and a value greater than zero would be any positive number except zero. - Ken White