I've got and switch statements like this:
switch(x){
case a:
executeSth();
executeA();
break;
case b:
executeSth();
executeB();
break;
...
}
so executeSth(); should allways be executed except in default case but after it some case specific code is called (executeA(); or executeB() and so on). (So simply putting it in front of the switch doesn't work).
Is there an efficient way to reduce the number of "executeSth();" without sacrificing performance?
I could only imagine split it into two switches (one that executes the executeSth() in and one that executes the specific code) but that would sacrifice performance. Maybe you got better ideas?
I'm basicly interessed in code for c/c++ or php. My goal is to minimize code size and in case of c/c++ the size of the resulting executable.
Edit: Yes, the order of the functions matters. Edit2: I don't have the choice between php or c++, I need it both to be as good as possible.
switch
is an option...This uses two switches, but the second is not triggered in the default
case so has a slightly better performance profile than just two in-line switches.
switch($x) {
case a: case b: case c:
executeSth();
switch($x) {
case a:
executeA();
break;
case b:
executeB();
break;
case c:
executeC();
break;
}
break;
default:
...
}
This is a PHP option which may work, though a lot of people don't like variable functions. This is probably the best option if you want to totally remove nesting & repetition.
switch($x) {
case a:
$function = "executeA";
break;
case b:
$function = "executeB";
break;
case c:
$function = "executeC";
break;
default:
...
}
if(isset($function)) {
executeSth();
$function();
}
I've also made a little live test bed here, if anyone wants to test their PHP solutions work before posting them (case 10
should executeSth()
and executeA()
, case 20
should executeSth()
and executeB()
, default
should executeDefault()
).
I had a total brain fart when I wrote this, thankfully idipous reminded me that we can do this with a simple function pointer.
// Declare function pointer
int (*functionCall)() = NULL;
// In switch statement, assign something to it
functionCall = &execute;
// After the switch statement, call it
int result = (*functionCall)();
Note: I'm out so haven't checked the syntax on these. The syntax I've used is C syntax and may require some small changes to work in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With