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

It returns the difference at the octet that differs. In your example '\0' < '2' so something negative is returned.


C11 quotes

C11 N1570 standard draft

I think "dog" < "dog2" is guaranteed by the following quotes:

7.23.4 Comparison functions 1 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.

So the chars are interpreted as numbers, and '\0' is guaranteed to be 0:

Then:

7.23.4.2 The strcmp function 2 The strcmp function compares the string pointed to by s1 to the string pointed to by s2.

says that, obviously, strings are compared, and:

7.1.1 Definitions of terms 1 A string is a contiguous sequence of characters terminated by and including the first null character.

says that the null is part of the string.

Finally:

5.2.1 Character sets 2 [...] A byte with all bits set to 0, called the null character, shall exist in the basic execution character set; it is used to terminate a character string.

so '\0' is equal to zero.

Since the interpretation is as unsigned char, and all chars are different, zero is the smallest possible number.


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<str2 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;
}

Tags:

C

Strcmp