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 ?

+4
source share
2 answers

No, you are comparing the values ​​of pointers (i.e.: addresses), not their contents. This code is not invalid, it probably does not do what you expect.

In C ++, you should avoid const char * and go to std::string :

 #include <string> std::string t1("test1"); std::string t2("test2"); if (t1 == t2) { /* ... */ } 
+6
source

This is true, but it does not do what you think. == on pointers checks if they point to the same memory address. If you have two identical lines in different places, this will not work.

If you are familiar with Python, this is similar to the difference between is and == in that language.

+3
source

Source: https://habr.com/ru/post/1333007/


All Articles