Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison in C++

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?

like image 925
kay Avatar asked Jan 21 '23 21:01

kay


2 Answers

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) {
    /* ... */
}
like image 107
icecrime Avatar answered Jan 23 '23 11:01

icecrime


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.

like image 25
dan04 Avatar answered Jan 23 '23 09:01

dan04