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?

5
Contributors
5
Replies
10
Views
10 Years
Discussion Span
Last Post by Nikolay_2
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.

Votes + 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 ;

:)

0

strcmp compare the strings. it is more like following java / php code:

if (a > b)
return 1
else if (a < b)
return -1
else
return 0

however, C++ compiller is smart enought and it optimizes codes like those:

if (strcmp(a, b) == 0)
...
if (strcmp(a, b) != 0)
...

those code is compiled using non standard function similar to ==.

finally, there is std::string.compare() - this is same as strcmp() but for std::string

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.