3

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

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

d r likely was referring to c++11.
I just responded to the question as asked. It wouldn't be the first time I've seen someone ask a question based on an assumption of C++-specific features being part of C. Think how many folks believe they are writing C code, even when they use operator new.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.