0

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.

3
Contributors
3
Replies
6
Views
9 Years
Discussion Span
Last Post by vijayan121
Featured Replies
  • 2
    Duoas 1,025   9 Years Ago

    Both your teachers are full of crap. Use ==. Keep in mind, though, that == is limited to an [I]exact[/I] match comparison and only returns bool. You can get a little more information back using functions like [B]string.compare()[/B]. Hope this helps. [EDIT] I should give a little more info. For … Read More

2

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:

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
}
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.