Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing LPCWSTR in if()

I feel like I am missing something very obvious here...

In my program, I read user input from an edit box using GetWindowText(),
followed by this code:

if (x == L"R" || x == L"C" || x == L"L"){ n = 1; }
else{ n = 9; }

The debugger clearly says that x is L"R", but n is getting set as 9.

debugger

Is using if() in this situation wrong and should I use something else?

like image 363
Pavel Pilař Avatar asked May 10 '26 09:05

Pavel Pilař


1 Answers

x is a wchar* pointer. The debugger is smart enough to show you the data that x is pointing at. The actual data is elsewhere in memory.

L"R" and the other values are string literals. They are implemented as pointers to wchar_t[] arrays stored in your app's read-only data segment.

Your if statement is comparing pointers to pointers, which will fail if they are not pointing at the same memory (in this case, they do not). To compare the actual data being pointed at, you need to use lstrcmpW() or similar function, eg:

if ((lstrcmpW(x, L"R") == 0) ||
    (lstrcmpW(x, L"C") == 0) ||
    (lstrcmpW(x, L"L") == 0))
{
    n = 1;
}
else
{
    n = 9;
}
like image 81
Remy Lebeau Avatar answered May 12 '26 23:05

Remy Lebeau