Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Using if-else conditional statements for each case is a simple solution that comes first to mind.</p> <p>For example:</p> <pre><code>int game(int i){ if(i == 1){ //first case code here. } else if(i == 2){ //second case code here. } //.... return 0; } </code></pre> <p>The code in each case can even be put in other functions that will be invoked depending on each condition. This will probably be enough for your case.</p> <p>A more flexible solution (but much more complex) is a <strong><em>dispatch table</em></strong>. The idea is to have separate functions with each desired functionality, and put pointers of them in an array. Then, you can call them by indexing the table, using those function pointers. This can be extremely helpful if you have a sequence of executions (function invokes) to be done and you want to set it done easily, or you want to have different results depending on your input, without changing your program.</p> <p>There is an example below. This code can be used in C too, if you replace std::cout with printf and <em>iostream</em> with <em>stdio</em> library.</p> <pre><code>#include &lt;iostream&gt; using namespace std; // Arrays start from 0. // This is used for code // readability reasons. #define CASE(X) X-1 typedef void (*chooseCase)(); // Functions to execute each case. // Here, I am just printing // different strings. void case1(){ cout&lt;&lt; "case1" &lt;&lt; endl; } void case2(){ cout&lt;&lt; "case2" &lt;&lt; endl; } void case3(){ cout&lt;&lt; "case3" &lt;&lt; endl; } void case4(){ cout&lt;&lt; "case4" &lt;&lt; endl; } //Put all the cases in an array. chooseCase cases[] = { case1, case2, case3, case4 }; int main() { //You can call each scenario //by hand easily this way: cases[CASE(1)](); cout &lt;&lt; endl; //Idea: You can even set in another // array a sequence of function executions desired. int casesSequence[] = { CASE(1), CASE(2), CASE(3), CASE(4),CASE(3),CASE(2),CASE(1) }; //Execute the functions in the sequence set. for(int i = 0; i &lt; (sizeof(casesSequence)/sizeof(int)); ++i){ cases[casesSequence[i]](); } return 0; } </code></pre> <p>This will print at the output:</p> <pre><code>case1 case1 case2 case3 case4 case3 case2 case1 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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