strcmp() return values in C [duplicate]

I am learning about strcmp() in C. I understand that when two strings are equal, strcmp returns 0.

However, when the man pages state that strcmp returns less than 0 when the first string is less than the second string, is it referring to length, ASCII values, or something else?


Solution 1:

In this sense, "less than" for strings means lexicographic (alphabetical) order.

So cat is less than dog because cat is alphabetically before dog.

Lexicographic order is, in some sense, an extension of alphabetical order to all ASCII (and UNICODE) characters.

Solution 2:

A value greater than zero indicates that the first character that does not match has a greater value in the first string than in the second, and a value less than zero indicates the opposite.

Solution 3:

C99 7.21.4:

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.

Note in particular that the result doesn't depend on the current locale; LC_COLLATE (see C99 7.11) affects strcoll() and strxfrm(), but not strcmp().