Search code examples
cstringstrcmp

What is the ordering for `strcmp`'s return value?


I have a very small amount of code:

int test = strcmp("Websecurity", "easily");
printf("%d\n", test);

The result is -1. Why? Clearly 'W' is greater than 'e'?


Solution

  • The return value of strcmp depends on the encoding of the strings being compared. Per the Posix standard:

    From: http://pubs.opengroup.org/onlinepubs/009695399/functions/strcmp.html

    The sign of a non-zero return value shall be determined by the sign of the difference between the values of the first pair of bytes (both interpreted as type unsigned char) that differ in the strings being compared.

    In ASCII (and utf-8), capital letters are represented by lower byte values than lower-case letters. In particular, 'W' is 0x57, and e is 0x65. Therefore, you are guaranteed a negative return value.