0

I'm trying to compare in my C-program a string and a LPCTSTR.

Here's what i've done so far (the code has been simplified to only what's problematic) :

DWORD main(DWORD ac, LPCTSTR *av)
{
    DWORD cpt = 1;

    while (++i < ac)
    {
        if (strcmp(av[i], "value"))
            printf("1 : OK\n");
        else if (strcmp(av[i], _T("value")))
            printf("2 : OK\n");
        else if (strcmp(av[i], (LPCTSTR)"value"))
            printf("3 : OK\n");
    }
    return EXIT_SUCCESS;
}

When I execute my program with the first parameter "value", it appears that none of the if are verified. I tried with strcmp and lstrcmp but the results are the same.

Can someone tell me what I'm doing wrong please ?

Thanks.

BMN
  • 8,253
  • 14
  • 48
  • 80
  • Also note that your code isn't going to work if UNICODE is defined, i.e. when LPCTSTR is actually a `const wchar_t*` (or `unsigned short*`) and not a `const char*`. IMO you should be building Windows apps in Unicode as a rule anyway. – Rup Mar 09 '12 at 12:34

1 Answers1

3

strcmp and family return 0 to indicate that the strings are equal. Your logic is simply the wrong way around.

You should write the test like this:

if (strcmp(av[i], "value")==0)

As an aside, the other two if statements, comparing with _T("value") and (LPTSTR)"value" are fine when compiling for ANSI, but are incorrect when compiling for Unicode. When compiling for Unicode, _T("value") will evaluate to a wide string and therefore not be a valid argument for strcmp. That's a compile error. And (LPTSTR)"value" will also be a compile error because LPTSTR would be a wide string. But the cast would be completely bogus also. Anyway, I'm just mentioning these issues for completeness, but I do understand that these extra if statements were added whilst you were trying to debug the root problem.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Oh sh*t ! I don't know why in my mind strcmp returned 1 when both string were equals... Thanks ;) – BMN Mar 09 '12 at 14:12