what is 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 ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 intoif (0xdeadbeef == 0x0badcafe)which is obviously false.When you use
strcmp, you compare the content of each box until you reach\0in each of them. That’s why the second test returns true.If you change the first test to
if("some" == "some")then a compilermay potentiallysee that they are the same strings and will store them only once. Which means that your test will transform intoif (0x0badcafe == 0x0badcafe)which is obviously true.