0

I'm not quite sure the difference between strcmp and == operator when comparing 2 different strings, I was told to do this but == works as well with less typing.

if ((strcmp (a, b[i]) == 0))     
     {
          someMethod();
      }
else
    someOtherMethod();
_______________________________
if (a==b))     
     {
          someMethod();
      }
else
        someOtherMethod();

Is any special reason to use to choose one over the other for comparing 2 strings?

4
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by thekashyap
Featured Replies
  • 1
    Narue 5,707   9 Years Ago

    >I'm not quite sure the difference between strcmp and == operator when comparing 2 different strings Presumably you're using C-style strings, otherwise strcmp wouldn't be an option. So with that in mind, you should use strcmp because it compares the contents of the strings while == compares the address of … Read More

  • Also, strcmp will tell you the relative ordering of the strings rather than simply if they are equal, if you needed that as well. Read More

1

>I'm not quite sure the difference between strcmp and == operator when comparing 2 different strings
Presumably you're using C-style strings, otherwise strcmp wouldn't be an option. So with that in mind, you should use strcmp because it compares the contents of the strings while == compares the address of the first elements in the strings. Given the following comparison:

char a[] = "test";
char b[] = "booga";

if ( a == b ) {
  // Stuff
}

This comparison is functionally equivalent:

char a[] = "test";
char b[] = "booga";

if ( &a[0] == &b[0] ) {
  // Stuff
}

That's a huge difference from the intended operation of comparing each character in the two strings for equality. In that case, you use strcmp.

Comments
Good Explaination
1

Also, strcmp will tell you the relative ordering of the strings rather than simply if they are equal, if you needed that as well.

0

I see... just read about c-type strings vs c++ strings, now I know why my == didn't work with grabbing and comparing stuff of the commandline that uses char *argv[].
cheers

0

Just to add the fact that this is type independent (i.e. not specific to char*):
operator == is overloaded/implemented for all basic types in C++. A pointer is also a basic type. The implementation of operator == that compares pointers is NOT to compare what they to point to but instead it compares the values of pointers. As we know the value of a pointer is the address of object it's pointing to.

As "char*" is the usual substitute for a string, it's very common to see this mistake. But same is applicable to int*, float*,...void*

Another place where you see this error is:

std::map< char*, my_value_class > my_map ;

:)

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.