Search code examples
cstrcmp

When will strcmp not return -1, 0 or 1?


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.


Solution

  • In the C99 standard, §7.21.4.2 The strcmp function:

    The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

    Emphasis added.

    It means the standard doesn't guarantee about the -1, 0 or 1; it may vary according to operating systems.

    The value you are getting is the difference between w and h which is 15.

    In your case hello and world so 'h'-'w' = -15 < 0 and that's why strcmp returns -15.