Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>A nested <code>switch</code> is an option...</h2> <p>This uses two switches, but the second is not triggered in the <code>default</code> case so has a <em>slightly</em> better performance profile than just two in-line switches.</p> <pre><code>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: ... } </code></pre> <h2>Alternatively, a variable function may do the job...</h2> <p>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 &amp; repetition.</p> <pre><code>switch($x) { case a: $function = "executeA"; break; case b: $function = "executeB"; break; case c: $function = "executeC"; break; default: ... } if(isset($function)) { executeSth(); $function(); } </code></pre> <p>I've also made a little <a href="https://eval.in/46491" rel="nofollow">live test bed here</a>, if anyone wants to test their PHP solutions work before posting them (<code>case 10</code> should <code>executeSth()</code> and <code>executeA()</code>, <code>case 20</code> should <code>executeSth()</code> and <code>executeB()</code>, <code>default</code> should <code>executeDefault()</code>).</p> <h2>In C++, you can use a function pointer to achieve the same as the above</h2> <p>I had a total brain fart when I wrote this, thankfully idipous reminded me that we can do this with a simple function pointer.</p> <pre><code>// Declare function pointer int (*functionCall)() = NULL; // In switch statement, assign something to it functionCall = &amp;execute; // After the switch statement, call it int result = (*functionCall)(); </code></pre> <p>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++.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload