Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does c++ compare two string using ==?

Tags:

c++

string

I came across a very simple but confusing problem today.

#include <iostream>
#include <string>
using namespace std;

int main(){
    string str = "123";
    string a = "1";
    string b = "1";

    cout << ((str[0]+"") == a) << endl;
    cout << (a==str.substr(0,1)) << endl;
    cout << (a==b) << endl;

}

The output is: 0 1 1

Why the first compare statement is false? How does c++ compare two string when using == operator?

like image 217
Tao Huang Avatar asked Mar 08 '26 14:03

Tao Huang


2 Answers

str[0]+"" is something rather odd - you take the numeric value of the first character (which is 49, assuming an ASCII encoding of the character '1'), and add it to a pointer to the start of an empty string. This gives you an invalid pointer, and undefined behaviour.

If you wanted to make a string out of the first character, that would be one of

string(1, str[0])
string(str, 0, 1)
str.substr(0, 1)
string() + str[0]

which would compare equal to a

like image 148
Mike Seymour Avatar answered Mar 10 '26 05:03

Mike Seymour


They are different types,the result of the expression str[0]+"" is char * type(""is char * not string,for char * the operator + is not overloaded,so its behavior is undefined), but a is string type, obviously they are not equal.To see reason,you can run this code:

cout<<typeid(str[0]+"").name()<<endl;
cout<<typeid(a).name()<<endl;
like image 40
mude918 Avatar answered Mar 10 '26 04:03

mude918



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!