|
|
This article does not cite any references or sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed. (February 2007) |
In POSIX and in the programming language C, strcmp is a function in the C standard library (declared in string.h) that compares two C strings.
The prototype according ISO/IEC 9899:1999, 7.21.4.2
int strcmp(const char *s1, const char *s2);
strcmp returns 0 when the strings are equal, a negative integer when s1 is less than s2, or a positive integer if s1 is greater than s2, according to the lexicographical order.
A variant of strcmp exists called strncmp that only compares the strings up to a certain point.
Example
#include <stdio.h> #include <stdlib.h> #include <string.h> int main (int argc, char **argv) { int v; if (argc < 3) { fprintf (stderr, "This program takes 2 arguments.\n"); return EXIT_FAILURE; } v = strcmp (argv[1], argv[2]); if (v < 0) printf ("'%s' is less than '%s'.\n", argv[1], argv[2]); else if (v == 0) printf ("'%s' equals '%s'.\n", argv[1], argv[2]); else if (v > 0) printf ("'%s' is greater than '%s'.\n", argv[1], argv[2]); return 0; }
The above code is a working sample that prints whether the first argument is less than, equal to or greater than the second.
A possible implementation is (P.J. Plauger, The Standard C Library, 1992):
int strcmp (const char * s1, const char * s2) { for(; *s1 == *s2; ++s1, ++s2) if(*s1 == 0) return 0; return *(unsigned char *)s1 < *(unsigned char *)s2 ? -1 : 1; }
However, most real-world implementations will have various optimization tricks to reduce the execution time of the function. One will notice, that strcmp not only returns -1, 0 and +1, but also other negative or positive values, resulting from optimizing away the branching introduced by the ?: operator:
return *(const unsigned char *)s1 - *(const unsigned char *)s2;
| This computer programming-related article is a stub. You can help Wikipedia by expanding it. |
This entry is from Wikipedia, the leading user-contributed encyclopedia. It may not have been reviewed by professional editors (see full disclaimer)




