Reputation: 159
I've been working on a project in class and the code I have written so far works well. A big part of my code uses nested switch statements. While I'm going to turn it in the way it is now, I would like to know for future reference if nested switch statements are generally frowned upon.
Upvotes: 3
Views: 6614
Reputation: 186
Generally speaking, if and switch statements are more "costy" in terms of calculations for the proccessor, because you force the assembler to make new guesses (for what the next instructions will be) every time you jump from case to case. Try to use as less possible if your prime concern is algorithm efficiency.
Upvotes: 0
Reputation: 9959
As you've probably noticed, because you asked, they're not exactly the easiest things to follow, so I would generally try to avoid them where possible.
This doesn't mean you can't do that kind of control flow - the trick being to split the cases out into their own functions. This lets someone read the top level switch, comprehend its branches and what happens (because you'll of course have given your functions good, descriptive names), and then they can examine each function in turn to understand the next level if they need to.
To avoid the cost of a function call which would previously have been unnecessary you can mark the functions inline
to make the compiler effectively copy the body of the function to the call site.
It'd end up looking something like this incredibly genericised and incomplete skeleton:
int main() {
int thing;
char second_level_thing;
// various code which produces thing and second_level_thing
switch (thing) {
case 0: do_zero_case(second_level_thing); break;
case 1: do_one_case(); break;
default: do_default_case(); break;
}
// the rest of main
}
inline void do_zero_case(char second_level_thing) {
switch (second_level_thing) {
case 'a': // 0 -> a branch code
// etc...
}
}
// etc...
Do not call your functions things like do_zero_case
! Name them after what it actually does.
I would add that if multiple levels are inspecting the same value there's something very odd going on.
There are also alternative control flows available through use of OOP techniques (virtual method calls in a variety of forms), templates, higher-order functions and so forth. Sometimes a nice simple switch
statement or two is exactly what you need though!
Upvotes: 4