What does strcmp return if two similar strings are of different lengths?

后端 未结 5 1222
庸人自扰
庸人自扰 2021-02-19 15:09

I understand that if you have \'cat\' (string1) and \'dog\' (string2) in strcmp (this is a C question) then the return value of strcmp would be less than 0 (since \'cat\' is lex

5条回答
  •  梦谈多话
    2021-02-19 15:31

    It is defined in the C standard as the difference between the first two non matching characters, but the implementation is wild. The only common point is that the return value is zero for equal strings, then respectively <0 or >0 for str1 and str1>str2. From ISO/IEC 9899:201x, §7.23.4 Comparison functions:

    The sign of a nonzero value returned by the comparison functions memcmp, strcmp, and strncmp is determined by the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char) that differ in the objects being compared.

    But some implementations take care to return typical values as 0, 1 and -1. See i.e. the Apple implementation (http://opensource.apple.com//source/Libc/Libc-262/ppc/gen/strcmp.c):

    int
    strcmp(const char *s1, const char *s2)
    {
        for ( ; *s1 == *s2; s1++, s2++)
        if (*s1 == '\0')
            return 0;
        return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
    }
    

    EDIT: In the Android boot library for Donut-release (https://android.googlesource.com/platform/bootable/bootloader/legacy/+/donut-release/libc/strcmp.c) the function returns 0 if strings are equal and 1 for the other 2 cases, and are used only logical operations:

    int strcmp(const char *a, const char *b)
    {
        while(*a && *b) {
            if(*a++ != *b++) return 1;
        }
        if(*a || *b) return 1;
        return 0;
    }
    

提交回复
热议问题