c++stringmfclpcstr

Comparing two LPCSTR with ==


I found out an implementation that compares two LPCSTR doing the following:

void check(LPCSTR lpText)
{
    if(lpText == input)
    {
         // do stuff
    }
}

The problem is that it works. I replaced it with...

if(lstrcmpi(lpText, input) == 0)
{
    // do stuff
}

and though I feel safer now.

I just wanted to know if the other implementation was just checking the addresses or the sizes, how did it work?

I checked the memory address of one LPCSTR and it is 0x0633522c and the other is 0x028a91a4.

This shakes my entire foundation.


Solution

  • Probably input in your first example is a CString instance, and there is an overload of operator== taking a raw C-style string pointer and a CString (const CString&), that does the right thing of string comparison.

    In fact, in cstringt.h ATL header file, you can find:

    friend bool operator==(
        _In_z_ PCXSTR psz1,
        _In_ const CStringT& str2) throw()
    {
        return( str2.Compare( psz1 ) == 0 );
    }