logical operations for const char *

I have a simple question! why is this not true?

(d == "cplusplus")

when

const char *d = "cplusplus";


how should I do the comparison then?
You are comparing pointer values and not the contents of the string. If you want such intuitive comparison switch to Standard C++ string class or still want to use char *, then use strcmp(..) function for example.
use std::string (if you want to use == ) OR strcmp() function.

If you have
const char * a = "cplusplus";
const char * b = "cplusplus";
const char * d = "cplusplus";
a,b and c are not pointing to the same address. There are three strings for which the compiler has allocated memory in the static area. Hence the address is different. The compiler does not peek inside the string to see the contents of the strings ( if they are already present or not).

The 'value' of "cplusplus" is actually the address in memory where it is stored.

So when you compare a const char* with the literal "cplusplus" you are comparing two memory addresses, NOT the data contained at those addresses.

Use:
 
strcmp(d, "cplusplus")

Or better still use std::string
1
2
3
std::string d = "cplusplus";

(d == "cplusplus") // now works as expected 
Also, in the future, don't post the same question in multiple forums.
1
2
3
std::string d = "cplusplus";

(d == "cplusplus") // now works as expected 


When you delve deeper into C++, above is C++ operator overloading mechanism at work. Something not available in Java yet.
Thanks a lot guys. It makes sense. And thanks Galik you solved my problem!

P.S. sorry for posting on two forum, I didn't know which one was relevant
If you have
const char * a = "cplusplus";
const char * b = "cplusplus";
const char * d = "cplusplus";
a,b and c are not pointing to the same address.


Not necessarily, anyway. Depending on how the compiler optimizes, they [i]might[i] point to the same space... or they might not.

But it's all the more reason not to try this. The behavior is inconsistent.
Well that does mean that compiler needs to save the string and compare all of them before saving the next one. Does the standard say any thing about the pointer address?
Topic archived. No new replies allowed.