d r
d r

Reputation: 41

comparison between std:string and c-string

I am trying to verify the answer(s) given on a similar question. I have a trouble with them, as the below code shows that effectively the content of std::string is compared with the content of char[], not the pointer(s).. as those answers suggest.

Is this a new feature of C++11? Any help highly appreciated.

std::string smth = "hello";
char ch[8] = "hello";
if (ch == smth)
    cout << "yes!";
else
    cout << " no ";

ch[2] = 'W';

if (ch == smth)
    cout << "yes!";
else
    cout << " no ";

ch[2] = 'l';
if (ch == smth)
    cout << "yes!";
else
    cout << " no ";

the output is: yes! no yes!, while the pointers definitely do not change..

Upvotes: 3

Views: 6593

Answers (3)

Peter
Peter

Reputation: 36597

The ability to compare a std::string with a const char *, and the result being comparison of the set of characters, is specified in every version of the C++ standard. Specifically, an operator==() and other comparison operators involving a std::string as at least one operand is part of the standard.

It is not a feature of any version of C, since std::string is not part of the C standard library. So it is not a feature of C11.

Upvotes: 2

Brandon
Brandon

Reputation: 53

The question you linked was comparing two values of type char*. The difference here is that char* is a pointer, but string() is not a pointer. When you compare pointers, it checks if the pointers are equal, but since string() isn't a pointer, it goes to its operator== which checks for equality in the string content itself.

Upvotes: 1

Aracthor
Aracthor

Reputation: 5907

The std::string does have an operator== with char* pointers.

So each time you execute the line:

if (ch == smth)

You don't just compare pointers, but call a function similar to strcmp that will compare string's and pointer's data and return true if they are similar.

So no, pointers definitely do not change, but their data do. So the operator's result as well.

Upvotes: 7

Related Questions