baoky chen
baoky chen

Reputation: 837

How can I call switch case 4 from case 5?

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.

Upvotes: 1

Views: 2568

Answers (4)

Simon Wang
Simon Wang

Reputation: 2963

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

Upvotes: 1

M4rc
M4rc

Reputation: 503

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.

Upvotes: 1

PherricOxide
PherricOxide

Reputation: 15929

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;
}

Upvotes: 3

Marc-Christian Schulze
Marc-Christian Schulze

Reputation: 3264

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

Upvotes: 1

Related Questions