Difference between strcmp of string.h and my own implementation of strcmp

Viewed 213

The first printf gives output as -1, whereas the second printf gives output as -115.

#include<stdio.h>
#include<string.h>
int mystrcmp(char*s, char*t){
    for(;*s==*t;s++,t++){
        if(*s=='\0'){
            return 0;
        }
    }
    return (*s-*t);
}
int main()
{
    char *y,*x="this";
    y="thiss";
    printf("%d\n\n",strcmp(x,y));
    printf("%d",mystrcmp(x,y));
    return 0;
}

I understand, that in my implementation, the code is calculating 0(ASCII of Null) - 's'(ASCII value 115). Can anyone please help me as to how I may exactly duplicate the working of strcmp function that is in string.h

3 Answers

The exact values returned from strcmp in the unequal cases aren't defined explicitly. In your particular case, any negative value is considered valid. From the man page:

The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

So the only guarantee is that if the first argument is "less than" the second then the result is negative, and if the first is "greater than" the second then the result is positive. Different implementations may return different values for the same strings.

As an example, if I compile and run your code on my machine with optimization set at -O0, I get back -115 from strcmp. If I change the optimization to -O1, it returns -1 instead. So not only can the result change from one machine to the next, but it can even vary on the same machine with different compiler settings.

The implementation of the "real" strcmp on your platform is most likely close to this code:

int strcmp(const char *s, const char *t) {
    for(; *s == *t; s++, t++) {
        if (*s == '\0') {           // are we at the end ?
            return 0;               // yes
        }
    }
    return (*s-*t) > 0 ? 1 : -1;   // return either +1 or -1
}

BTW: it should be int strcmp(const char *s, const char *t) instead of int strcmp(char *s, char *t)

The manuel page said that strcmp() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2. Your can try this code :

    int ft_strcmp(const char *s1, const char *s2)
{
    while ((unsigned char)*s1 || (unsigned char)*s2)
    {
        if ((unsigned char)*s1 != (unsigned char)*s2)
            return ((unsigned char)*s1 - (unsigned char)*s2);
        s1++;
        s2++;
    }
    return (0);
}
Related