2

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?

3
  • possible duplicate of Differences between C++ string == and compare()? Commented Apr 17, 2015 at 11:57
  • 5
    What do you think is the type of str[0]? Commented Apr 17, 2015 at 11:59
  • @DeepBlackDwarf I wouldn't call it a duplicate even though the titles are nearly the same. The root of the problem here is indexing a string with a character. Commented Apr 17, 2015 at 11:59

2 Answers 2

11

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

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

1 Comment

Thanks! I forgot that when using + to combine two strings, at least one of the operands must be string type. str[0] + "" violates this rule.
1

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;

3 Comments

I don't know which one you refer to ?
str[0]+"". It's char + char const[0]. If the arguments were in the different order, then I would understand the result of char*. But as it is I think the result would be char. I'm not sure.
It's char*,you can test it using the code in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.