Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparison between std:string and c-string

Tags:

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

like image 651
d r Avatar asked Dec 29 '25 13:12

d r


1 Answers

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.

like image 112
Aracthor Avatar answered Dec 31 '25 06:12

Aracthor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!