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..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With