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;
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 28, 2013 at 21:12
\$\endgroup\$

1 Answer 1

7
\$\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;
}
answered Sep 28, 2013 at 21:52
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Your first version is excellent; it would have been better to end your response there. =) \$\endgroup\$ Commented Sep 28, 2013 at 22:04

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.