HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Function equivalent to strcmp()

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
strcmpfunctionequivalent

Problem

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;
}

Solution

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;
}

Code Snippets

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

Context

StackExchange Code Review Q#31953, answer score: 7

Revisions (0)

No revisions yet.