# Function equivalent to strcmp()

I'm starting out and need feedback in order to discover the things I'm doing wrong.

This is supposed to behave like strcmp():

int compare(char *str1, char *str2)
{
while(*str1 || *str2)
{
if(*str1 != *str2)
{
break;
}
++str1;
++str2;
}
return *str1 - *str2;
}


How can it be improved? Are there any flaws?

Also, would any of the following styles be considered better?

int compare(char *str1, char *str2)
{
while((*str1 || *str2) && *str1 == *str2)
{
++str1;
++str2;
}
return *str1 - *str2;
}


int compare(char *str1, char *str2)
{
while((*str1 || *str2) && *str1 == *str2) ++str1, ++str2;
return *str1 - *str2;
}


You can skip the check for the end of one of the strings. If the other string ends before the one that you check the length for, the comparison of the characters will catch the difference:

int compare(char *str1, char *str2) {
while (*str1 && *str1 == *str2) {
str1++;
str2++;
}
return *str1 - *str2;
}


You can write the same using a for statement if you want it shorter (and less readable):

int compare(char *str1, char *str2) {
for (;*str1 && *str1 == *str2; str2++) str1++;
return *str1 - *str2;
}


Just for the sake of it, you can make is shorter (mis)using recursion, but that is a rather terrible solution:

int compare(char *str1, char *str2) {
return (*str1 && *str1 == *str2) ? compare(++str1, ++str2) : *str1 - *str2;
}

• Your first version is excellent; it would have been better to end your response there. =) Sep 28, 2013 at 22:04