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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With