Re: Names?

From: Daniel A. Koepke (
Date: 05/03/00

On Thu, 4 May 2000, Chris Maniar wrote:

> strcmp() returns NULL if the strings match.

Actually, you're incorrect.  strcmp() returns zero (0) if the strings
match.  The actual description of its return value is something akin to,
"strcmp(s0, s1) returns less than, equal to, or greater than zero if the
string s0 is less than, equal to, or greater than the string s1."  In
other words, it's a character-by-character difference comparison:

    strcmp("a", "b") == -1
    strcmp("b", "a") ==  1
    strcmp("a", "c") == -2
    strcmp("c", "a") ==  2

E.g., "a" is one less than "b," "b" is one more than "a," "a" is two less
than "c," "c" is two more than "a."  (We probably all know this from the
alphabet: 'A' is the first letter, 'B' the second, 'C' the third.  Thus,
the difference of the position of C (three) and of A (one) is two.)  When
dealing with complete strings, the comparison is not really any different:
we compare them character-by-character until we reach the end of both
strings or we find a difference (note that we don't continue to compare
the strings after we find a difference, instead returning that difference

One important caveat is that the comparison strcmp() makes is NOT
alphabetical.  It's ASCII, so the difference between the strings "ab" and
"abc" is not -3 (the alphabetic position of 'c') as you might expect, but
-99 (where 99 is the ASCII code for 'c').  As with subtraction, the order
of arguments to strcmp() is significant.  Using the previous example of
"ab" compared to "abc":

    strcmp("ab", "abc") == -99
    strcmp("abc', "ab") ==  99

Remember that in both cases, extending the string "abc" to be "abcdefghi"
does not effect the outcome: we return after we find our first difference
or if we reached the end of both strings without a difference.

This is useful for sorting algorithms (for instance, qsort(), which is
part of the standard C library) if you want to sort a list of strings or
sort other data based on a list of strings.


     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     |  |

This archive was generated by hypermail 2b30 : 04/10/01 PDT