简体   繁体   中英

is this a good way to do a strcmp to return false when strings are empty

I want another condition --still maintaining a fast execution time but safer -- where i return false if either or both strings is empty:

int speicial_strcmp(char *str1, char* str2 )
{

    if(*str1==*str2 =='\0')
         return 0;

     return strcmp(str1,str2);

}

No, that's not a good way to do it, because it doesn't work.

if(*str1==*str2 =='\0')

will get evaluated as:

bool tmp1 = *str1==*str2;
bool tmp2 = tmp1 == '\0';
if (tmp2)

In other words, because the bool will get promoted to an integer, your test will return true whenever the strings start with different characters ( tmp1 will be false, which gets converted to 0, and so tmp2 becomes true)

Don't try to outsmart the compiler. Writing fast code is not about writing as few lines of code as possible, or even as short lines as possible. Even if chaining together == in this manner was meaningful, there's no reason why it'd be faster. Just write code that you understand, and can write correctly.

即使您正确执行了建议的早期测试,也不太可能通过执行此类操作使速度更快strcmp已经或几乎已经执行了此操作。

Here's the code for strcmp() :

int
strcmp (p1, p2)
     const char *p1;
     const char *p2;
{
  register const unsigned char *s1 = (const unsigned char *) p1;
  register const unsigned char *s2 = (const unsigned char *) p2;
  unsigned reg_char c1, c2;

  do
    {
      c1 = (unsigned char) *s1++;
      c2 = (unsigned char) *s2++;
      if (c1 == '\0')
    return c1 - c2;
    }
  while (c1 == c2);

  return c1 - c2;
}

It's already as fast as it could meaningfully be. Your extraneous check only makes the cases you're not interested in, slower.

if( *str1 == 0 || *str2 == 0 )
   return 0;

The example you've given won't even run correctly. strcmp() will stop at the first differing characters. If both strings are empty, as satisfied by your "special case" above, this will be handled just as quickly as the example you've given.

By adding a special handler for both strings empty as above, you've only made the cases where they aren't, correspondingly slower.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM