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

后端 未结 5 1295
庸人自扰
庸人自扰 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:57

    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.

提交回复
热议问题