4

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?

Martin B
  • 23,670
  • 6
  • 53
  • 72
kay
  • 117
  • 1
  • 6

2 Answers2

6

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) {
    /* ... */
}
icecrime
  • 74,451
  • 13
  • 99
  • 111
  • 4
    Note to the OP: This works because `std::string` overloads the `==` operator so that a proper string comparison can be performed via a lexical comparison character-by-character. This is not true with `char*` pointers. – In silico Dec 22 '10 at 06:57
  • I see, but it magically works, is it due to compiler OPTIMIZATIONs that assign same address to both of these? – kay Dec 22 '10 at 06:57
  • 3
    @kay: yes, because both pointers point to string literals, chances are that the compiler re-uses the same one twice – icecrime Dec 22 '10 at 06:58
  • 1
    @kay: It "magically" works because the `std::string` class overloads the `==` operator so that it properly compares the actual strings and not the pointers to character arrays. – In silico Dec 22 '10 at 06:59
  • @kay: see [this question](http://stackoverflow.com/questions/690176/c-c-optimization-of-pointers-to-string-constants) which relates to your comment – icecrime Dec 22 '10 at 07:03
3

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.

dan04
  • 87,747
  • 23
  • 163
  • 198
  • 1
    Or `==` and `.equals()` in Java wrt objects. – Ignacio Vazquez-Abrams Dec 22 '10 at 07:01
  • I see, I was wondering why is it working and returning correct results, it seems when a program is getting compiled the compiler optimization procedures point t1 and t2 to the same memory address, regardless of the initial "test2" and later "test1" assignment to t2, – kay Dec 22 '10 at 07:01
  • 1
    @kay: Right, the compiler optimization is called "string pooling". Compilers nowadays have implemented this optimization (Visual C++ [has a compiler switch specifically for this](http://msdn.microsoft.com/en-us/library/s0s0asdt.aspx)). – In silico Dec 22 '10 at 07:02