954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

string compare

Is it safe to compare strings with == operator or is .compare recommended?

One of my teachers said NOT to use the == operator and always use a function when available. The example given was somthing along the lines of "when cpu is under high usage the == operator behaviour is unpredictable and will return false on the same two strings..."

Another C++ teacher in another situation said something along the lines of "it's easier to convert a char*array to the string class and use == instead of strcmp function."

I know both are talking about different things but I'm confused about the == issue.

rugae
Light Poster
27 posts since Mar 2007
Reputation Points: 10
Solved Threads: 0
 

Both your teachers are full of crap.

Use ==.

Keep in mind, though, that == is limited to an exact match comparison and only returns bool. You can get a little more information back using functions like string.compare().

Hope this helps.

[EDIT]
I should give a little more info.

For the first teacher: if system load were to affect your code then there is something seriously wrong with your compiler. Chances are that == just calls the compare function... (but I don't actually know, having not bothered to read the STL code for it).

For the second teacher: why waste time and space converting a C-string to a std::string when you have a function that will do what you want perfectly well without going through the long winded and wholly unnecessary effort... Kind of like this sentence, no?

@rugae, just smile and nod when they start spouting stuff about odd behavior and extra hoops. :wink:

Duoas
Postaholic
2,043 posts since Oct 2007
Reputation Points: 1,140
Solved Threads: 229
 

Roger that!

rugae
Light Poster
27 posts since Mar 2007
Reputation Points: 10
Solved Threads: 0
 

is a java programmer trying to teach c++?
in c++, == always means logical equivalence.
as the language is not pointer-disadvantaged, you can compare addresses (again with an ==) to check for identity.
the case is different in java; you cannot comare strings for equivalence using an ==. see http://www.beginner-java-tutorial.com/java-string-comparison.html

void compare( const std::string& a, const std::string& b )
{
  bool equivalent = a == b ; // a and b are logically equivalent
  bool identity_equal = &a == &b ; // a and b are the same string object
}
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You