3
\$\begingroup\$

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;
}
\$\endgroup\$
5
\$\begingroup\$

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;
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Your first version is excellent; it would have been better to end your response there. =) \$\endgroup\$ – 200_success Sep 28 '13 at 22:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.