Search code examples
visual-studio-2010visual-c++argvstrcmp

Using strcmp to compare argv item with string literal isn't working as I was expecting


I'm quite new to Visual C++ so this might be a 'schoolboy' error, but the following code is not executing as I'd expected:

#include "stdafx.h"
#include <string.h>

int _tmain(int argc, _TCHAR* argv[])
{
    if (strcmp((char*)argv[1], "--help") == 0)
    {
        printf("This is the help message."); //Won't execute
    }
    return 0;
}

The executable, named Test.exe is launched as follows

Test.exe --help

I was expecting the message This is the help message. but I'm not seeing it - debugging reveals that the if condition comes out as -1 and not 0 as I'd expect. What am I doing wrong?


Solution

  • OK, I've figured out what's going on. The argv[] array is declared as TCHAR*, which is a macro that adjust the type based on whether or not Unicode has been enabled for the project (wchat_t if it is or char if it is not). The strcmp function, which I was trying to use, is the non-Unicode string comparison while wcscmp is the Unicode equivalent. The _tcscmp function uses the appropriate string comparison function depending on the Unicode setting. If I replace strcmp with _tcscmp, problem solved!

    #include "stdafx.h"
    #include <string.h>
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        if (_tcscmp(argv[1], _T("--help")) == 0)
        {
            printf("This is the help message."); //Will execute :)
        }
        return 0;
    }
    

    The _T function converts the argument to Unicode, if Unicode is enabled.

    See also: Is it advisable to use strcmp or _tcscmp for comparing strings in Unicode versions?