1

I have a switch statement:

switch(choice)
{
case 1:
//some compute
break;
case 2:
//some compute
break;
case 3:
//some compute
break;
case 4:
//some compute
break;
case 5:
//Call case 3
//Call case 4
//perform my own function
break;
}

How do I call the function of case 3 and case 4 then perform my own computation at case 5.

The only way I could do is to run the same code of case 3 and then case 4 then my own computation, I wonder is there a way to call case 3 & 4 directly like calling a function then return back to case 5.

Mat
  • 202,337
  • 40
  • 393
  • 406
baoky chen
  • 799
  • 2
  • 11
  • 20

4 Answers4

3

You can't directly do that. You could put the case code in a function and then call that function though.

switch(choice)
{
case 1:
//some compute
break;
case 2:
//some compute
break;
case 3:
doCase3stuff();
break;
case 4:
doCase4stuff();
break;
case 5:
doCase3stuff();
doCase4stuff();
//perform my own function
break;
}
PherricOxide
  • 15,493
  • 3
  • 28
  • 41
1

Place your code in functions/methods and invoke them in the corresponding cases.

Marc-Christian Schulze
  • 3,154
  • 3
  • 35
  • 45
  • if i place them in a function, it will say some variable not declared etc as those variable are declare in main , what should i do – baoky chen Oct 13 '12 at 09:20
  • @baokychen Are your variables used to share/exchange information between your functions? if so you should use a class to pack your data and the corresponding functions. – Marc-Christian Schulze Oct 13 '12 at 09:22
  • 1
    @baokychen declare these variables in the function? Pass them as parameter? Define them as static? Define them as global? It depends on what this code is supposed to do. –  Oct 13 '12 at 09:22
1

My initial thought is that you could place it into a loop, and in case 5, change choice to 4. Or, if it's possible you could perform a recursive call, passing 4 as the choice instead of 5.

M4rc
  • 473
  • 2
  • 13
1

Then make case 3 and case 4 code as two functions so you can call it there with no duplicate code writing, otherwise you can only achieve that by goto which is not a good idea

Simon Wang
  • 2,843
  • 1
  • 16
  • 32