what i开发者_如何转开发s the difference between "some" == "some\0"
and strcmp("some","some\0")
in c++?
Why if("some" == "some\0")
returns false
and if(!strcmp("some","some\0"))
returns true
?
"some" == "some\0"
compares the string literals by their addresses. These literals are stored in different memory locations. So always false
.
!strcmp("some","some\0")
compares the contents of strings. Thus in that context "some\0"
is same as "some"
. So true
.
Edit: From your comments you ask that why "some" == "some"
is true
. That's because mostly compiler are smart enough to reuse the string literal(when they are stored in read only region). That's why it returns true
.
P.S. In below case "some" is not stored in read-only:
char a[] = "some";
See the following diagram. It shows two strings in memory, their content is in the box, beside the box you'll see the address of each one.
When you're doing if("some" == "some\0")
you are comparing the addresses. It is translated into if (0xdeadbeef == 0x0badcafe)
which is obviously false.
When you use strcmp
, you compare the content of each box until you reach \0
in each of them. That's why the second test returns true.
If you change the first test to if("some" == "some")
then a compiler may potentially
see that they are the same strings and will store them only once. Which means that your test will transform into if (0x0badcafe == 0x0badcafe)
which is obviously true.
The type of "some"
is const char*
, so when you compare "some"=="some\0"
you are comparing two const char*
pointers. Since they may not point to same memory location the comparison would usually fail. In the second case, you are using strcmp
which compares the strings by going through individual characters in the string.
精彩评论