开发者

Comparison in C++

开发者 https://www.devze.com 2023-01-31 13:42 出处:网络
Is this valid code in C++ in terms of comparing two const char * const char * t1=\"test1\"; const char * t2=\"test2\";

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=" << 开发者_如何学JAVAt1 << 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号