As the title of this question? What's the difference?
If I write:
char *cp = "a";
cout << (cp == "a") << endl;
or:
string str = "a";
cout << (str == "a") << endl;
They are the same and all return true. But if I write:
char *cp = "";
cout << (cp == "\0") << endl;
It returns false. But:
string str = "";
cout << (str == "\0") << endl;
It returns true.
I thought they should be the same from the pointer and array perspective. But they turn out to be different. What's the subtle difference between them? And how should I write a char array to represent an empty string?
OK, what's above the line might be unclear like somebody said it might be "a compiler optimization".
What I really want is this:
char *cp = "abcd";
can give me an array like this: ['a', 'b', 'c', 'd', '\\0']. I was wondering how can I use the similar syntax to get an array like this: ['\\0']. Because I tried:
char *cp = "";
And it seems not the right code. I thought it could give me what I want. But it doesn't.
Sorry for the ambiguousness above the line. I'm a newbie and I don't the that might be a compiler optimization.
String literals always have an implicit \\0
at the end. So ""
is of type const char[1]
and consists of one \\0
, whereas "\\0"
is of type const char[2]
and consists of two \\0
s. If you want the empty string literal, just write ""
. There is no need to insert another \\0
manually.
operator==(const char*, const char*)
compares pointers, not characters. If you compare two different string literals with ==
, the result is guaranteed to be false. (If you compare two string literals consisting of the same characters with ==
, the result is not well-defined.)
std::string::operator==(const char*)
treats the argument as a C string. That is, it will only read until it encounters the first \\0
. Hence, it cannot distinguish between ""
and "\\0"
.
The "\\0"
actually contains two '\\0'
characters, one of them created implicitly.
If you write something like
char *cp = "a";
cout << (cp == "a") << endl;
you are comparing two pointers, not the string contents (use strcmp()
to do so), while
std::string cp = "a";
cout << (cp == "a") << endl;
compares the contents up to the first found '\\0'
, because the bool std::string::operator==(const char*)
is overloaded to do so.
As for your edits:
Because I tried:
char *cp = "";
And it seems not the right code. I thought it could give me what I want. But it doesn't.
char* cp = "";
isn't exactly the same as
char cp[1] = { '\0' };
since the string literal is created with static storage location, while the array version allocates memory on the stack.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.