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.

Recommended Answers

All 3 Replies

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

Hope this helps.

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:

Roger that!

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

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.