The strcmp function compares two null terminated strings that have been passed as arguments to the function. The comparison is done character by character, and is case sensitive.

The strcmp function requires two arguments. The arguments are pointers to the first and second strings that need to be compared, respectively. If any of the arguments do not point to a valid null terminated string, the result of the function is unpredictable.

The return value of the strcmp function indicates how the two string compare using a lexicographic method. If the strings are equal, the return value is zero. If the first string comes before the second string in the lexicographic order, then the value -1 is returned. Otherwise, the value 1 is returned.

The following code shows an example of strcmp in use:

#include        <string.h>
#include        <stdio.h>

int main()
        char *s1 = "initial string";
        char *s2 = "second string";
        int res;
        res = strcmp(s1, s2);
        if (res == 0)
                printf("the first string is equal to the second\n");
        else if (res < 0)
                printf("the first string is less than the second\n");
        else if (res > 0)
                printf("the second string is less than the first\n");
        printf("the value is %d\n", res);
        return 0;

In a UNIX system, this code will print "the processor is available", and then proceed to execute the "ls" command, with a return value of zero

Article created on 2008-08-19 22:15:05

Post a comment