Is this valid code in C++ in terms of comparing two const char *
const char * t1="test1";
const char * t2="test2";
t2 = "test1";
if ( t1 == t2 ) {
cout << "t1=t2=" << t1 << endl;
}
without using strcmp
?
No, you are comparing the pointers values (ie: addresses), not their content. That code is not invalid, it just probably does not do what you expect.
In C++, you should avoid const char *
and go for std::string
:
#include <string>
std::string t1("test1");
std::string t2("test2");
if (t1 == t2) {
/* ... */
}
It's valid, but it doesn't do what you think it does. ==
on pointers checks whether they point to the same memory address. If you have two identical strings at different locations, it won't work.
If you're familiar with Python, this is similar to the distinction between is
and ==
in that language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With