switch case with wchar_t

Hello normally i use if to check but when i have a lot of conditions is very painful. So i was thinking to use a switch case like the most efficient way.. obviously looping but not good because the loops in my case is not good. the if will be:
1
2
3
4
5
static const wchar_t *example=L"myprogram.exe";
if (!lstrcmpW(((LVITEMW*)lparam)->pszText, example))//The lparam is a LVITEM* struct.
        {
            return 0;
        }


Now i will put like switch case:
1
2
3
4
5
6
7
switch ( ((LVITEMW*)lparam)->pszText ) {
  case "pro.exe":            // Note the colon, not a semicolon
    return 0;
    break;
  default:     
    break;
  }

Errors:
dllmain.cpp:29:40: error: switch quantity not an integer
switch ( ((LVITEMW*)lparam)->pszText ) {
^
:30:10: error: could not convert '"p\000r\000o\000.\000e\000x\000e\000\000"' from 'const wchar_t [8]' to '<type error>'
case L"pro.exe": // Note the colon, not a semicolon

Last edited on
As the compiler says: The switch variable has to be a const integral type known at compile time. The same with the cases - can't be strings.

Good Luck !!
you can do it, but its a pain. Clearly you know the strings you want to compare against at compile time. So you can put them in a vector and switch off the index...

for(...)
find index in vector of strings that matches the item

switch...
case 0: // your string matched whatever was in vect[0] location..
...

you can also do some sort of string to number algorithm and switch off the number. If the # of strings is huge, this might perform better than constant linear (or even binary) searches.


you can also make an enum off the strings as vector indices for a cleaner looking final solution...

enum{.... proexe, ...};
case proexe:

If the main concern is the size of the condition you could store the string as a variable and then compare it, which makes each if statement a bit shorter.

1
2
3
4
5
const wchar_t *txt = ((LVITEMW*)lparam)->pszText;
if (!lstrcmpW(txt, L"pro.exe"))
{
	return 0;
}

Or you could create a function or lambda to make it even shorter.

1
2
3
4
5
auto cmp = [&](const wchar_t* str){ return !lstrcmpW(((LVITEMW*)lparam)->pszText, str); };
if (cmp(L"pro.exe"))
{
	return 0;
}
Last edited on
the trouble was trying to switch off a non-integer.
but that will help if he swaps back to chained if-statements.
Topic archived. No new replies allowed.