Differences between C++ string == and compare()?
I just read some recommendations on using
std::string s = get_string();
std::string t = another_string();
if( !s.compare(t) )
{
instead of
if( s == t )
{
I'm almost always using the last one because I'm used to it and it feels natural, more readable. I didn't even know that there was a separate comparison function.
To be more precise, I thought == would call compare().
**What are the differences? In which contexts should one way be favored to the other?**
I'm considering only the cases where I need to know if a string is the same value as another string.
More
1 Expert Answer
There is no difference. operator== does use string::compare: http://www.cplusplus.com/reference/string/string/operators/
The functions use string::compare for the comparison.
I personally also prefer operator== when equality is all that matters.
Still looking for help? Get the right answer, fast.
Ask a question for free
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Find an Online Tutor Now
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Bikash J.
Internally, string::operator==() is using string::compare().09/26/21