Riko Ophorst Riko Ophorst - 3 months ago 14
C++ Question

Optimizing an if statement with over 50 OR's ( || )

Okay, so I'm doing some stuff involving keyboard input. I now have a giant function like this:

return key == BB_KEY_SPACE ||
key == BB_KEY_ZERO ||
key == BB_KEY_ONE ||
key == BB_KEY_TWO ||
key == BB_KEY_THREE ||
key == BB_KEY_FOUR ||
key == BB_KEY_FIVE ||
key == BB_KEY_SIX ||
key == BB_KEY_SEVEN ||
key == BB_KEY_EIGHT ||
key == BB_KEY_NINE ||
key == BB_KEY_A ||
key == BB_KEY_B ||
key == BB_KEY_C ||
key == BB_KEY_D ||
key == BB_KEY_E ||
key == BB_KEY_F ||
key == BB_KEY_G ||
key == BB_KEY_H ||
key == BB_KEY_I ||
key == BB_KEY_J ||
key == BB_KEY_K ||
key == BB_KEY_L ||
key == BB_KEY_M ||
key == BB_KEY_N ||
key == BB_KEY_O ||
key == BB_KEY_P ||
key == BB_KEY_Q ||
key == BB_KEY_R ||
key == BB_KEY_S ||
key == BB_KEY_T ||
key == BB_KEY_U ||
key == BB_KEY_V ||
key == BB_KEY_W ||
key == BB_KEY_X ||
key == BB_KEY_Y ||
key == BB_KEY_Z ||
key == BB_KEY_NUMPAD0 ||
key == BB_KEY_NUMPAD1 ||
key == BB_KEY_NUMPAD2 ||
key == BB_KEY_NUMPAD3 ||
key == BB_KEY_NUMPAD4 ||
key == BB_KEY_NUMPAD5 ||
key == BB_KEY_NUMPAD6 ||
key == BB_KEY_NUMPAD7 ||
key == BB_KEY_NUMPAD8 ||
key == BB_KEY_NUMPAD9 ||
key == BB_KEY_MULTIPLY ||
key == BB_KEY_PLUS ||
key == BB_KEY_SEPERATOR ||
key == BB_KEY_MINUS ||
key == BB_KEY_DECIMAL ||
key == BB_KEY_DIVIDE ||
key == BB_KEY_OEM1 ||
key == BB_KEY_OEMPLUS ||
key == BB_KEY_OEMCOMMA ||
key == BB_KEY_OEMMINUS ||
key == BB_KEY_OEMPERIOD ||
key == BB_KEY_OEM2 ||
key == BB_KEY_OEM3 ||
key == BB_KEY_OEM4 ||
key == BB_KEY_OEM5 ||
key == BB_KEY_OEM6 ||
key == BB_KEY_OEM7 ||
key == BB_KEY_OEM8 ||
key == BB_KEY_OEM102;`


Is there a good way to optimize this? I am assuming it takes a bit of processing power to verify all of this if-statement stuff. When looking at diagnostics it seems it's taking up a bit of time too. I'm wondering if there is a smarter way of doing this..

Answer

Making use of the additional information gleaned from the comments that key is a char type, there are 256 possible values for key. The return value for each of the possible values of key can be stored into a global array indexed by key, and retrieved by simply returning the key'th element of the array.

char arr[256] = { 0 };
arr[BB_KEY_SPACE] = 1;
arr[BB_KEY_ZERO] = 1;
/* ... */
arr[BB_KEY_OEM102] = 1;

f(char key)
{
    return arr[(unsigned)key]; /* == 1 for the BB_KEY_* values */
}


[ EDIT ] As originally suggested by @Galik in a comment, some memory could be saved (at a negligible speed penalty) by using a std::vector<bool> arr(256); instead of the char array.

Comments