More efficient alternative to compare booleans?

Started by
11 comments, last by slicksk8te 11 years, 6 months ago
Don't most [all?] compilers convert switches into jump tables anyway?[/quote]

Not all switches are converted to jump tables in C++. Only switch statements with contiguous integer cases starting from 0 AFAIK.
Advertisement

Don't most [all?] compilers convert switches into jump tables anyway?


Not all switches are converted to jump tables in C++. Only switch statements with contiguous integer cases starting from 0 AFAIK.
[/quote]
There's no reason why any range compact enough could be implemented as a jump table. Any offset from zero can be accounted for by subtraction before lookup, and missing cases can be accounted for with an entry jumping to the end of the case statement, or to wherever the no-case route goes.
This type of structure with a massive "if else if" is typically not the best style. The only way I see reducing this large block is to take a step back and see if you can group functionality in a different way. The way to tell if this will work is to look through all the body's of the if statements and see if they are unique. If they are not you can try and regroup the logic based on the statement bodies.

If you can't do this and you still want to have clean code, use a hash map as stated above because this will be the most efficient and expandable in the long term. Also rather than using individual booleans for A, B, C, and D, consider having a bit mask because it will make it easier to use as an index. For instance,
[source lang="cpp"]int ABCD = 0; // Flags variable

ABCD |= 1; // Set A
ABCD |= 2; // Set B

static Function functions[FUNC_NUM] = {
doSomething,
doSomethingElse,
...
}

int index = hash(ABCD);

function[index]();[/source]

This topic is closed to new replies.

Advertisement