Another reason strcmp()
returns the codes it does is so that it can be used directly in the standard library function qsort()
, allowing you to sort an array of strings:
#include <string.h> // for strcmp()
#include <stdlib.h> // for qsort()
#include <stdio.h>
int sort_func(const void *a, const void *b)
{
const char **s1 = (const char **)a;
const char **s2 = (const char **)b;
return strcmp(*s1, *s2);
}
int main(int argc, char **argv)
{
int i;
printf("Pre-sort:\n");
for(i = 1; i < argc; i++)
printf("Argument %i is %s\n", i, argv[i]);
qsort((void *)(argv + 1), argc - 1, sizeof(char *), sort_func);
printf("Post-sort:\n");
for(i = 1; i < argc; i++)
printf("Argument %i is %s\n", i, argv[i]);
return 0;
}
This little sample program sorts its arguments ASCIIbetically (what some would call lexically). Lookie:
$ gcc -o sort sort.c
$ ./sort hi there little fella
Pre-sort:
Argument 1 is hi
Argument 2 is there
Argument 3 is little
Argument 4 is fella
Post-sort:
Argument 1 is fella
Argument 2 is hi
Argument 3 is little
Argument 4 is there
If strcmp()
returned 1
(true) for equal strings and 0
(false) for inequal ones, it would be impossible to use it to obtain the degree or direction of inequality (i.e. how different, and which one is bigger) between the two strings, thus making it impossible to use it as a sorting function.
I don't know how familiar you are with C. The above code uses some of C's most confusing concepts - pointer arithmetic, pointer recasting, and function pointers - so if you don't understand some of that code, don't worry, you'll get there in time. Until then, you'll have plenty of fun questions to ask on StackOverflow. ;)