More Efficient way to code if then else statements in c++

c++, if-statement, switch-statement

Solution

You can convert the four booleans into a binary number 0..15, and use an array to look up the parameter, like this:

int location = (left   ? 1<<0 : 0)
             | (right  ? 1<<1 : 0)
             | (top    ? 1<<2 : 0)
             | (bottom ? 1<<3 : 0);

Now `location` has a number from 0 to 15, so you can do this:

int lookup[] = {-1, -1, -1, -1, -1, -1, -1,  1, -1, -1, -1, 3, -1, 4, 2, -1};
int arg = lookup[location];
if (arg != -1) {
    doSomething(arg);
}

Problem

I'm coding in c++ for the Nintendo DS, but this should be universal with all c++. I already know about switch statements, but I need to make a set of if, then, and else that have multiple arguments: ``` void doSomething(int number) { ... } bool left = true; bool right = false; bool top = false; bool bottom = false; if (left && top && right) doSomething(1); else if (top && right && bottom) doSomething(2); else if (left && right && bottom) doSomething(3); else if (left && top && bottom) doSomething(4); ``` Any help is appreciated.

Original source