IntroductionGo ToAllows us to jump unconditionally when required and it's not recommended to use Go To heavily. Switch..Case Statement allows to execute the case block based on the value of the variable or passed in switch, i.e., allow to do the condition base programming. ProblemIn my application, I reach stage where I have to execute code of the Case 1 of the Switch..Case and if some condition is satisfied, I have to execute the code of Case 3 of Switch..Case. Example
Switch(myvariable)
{case 1: …........if ( expression )
execute case 3:break;case 2:
…..
break;
case 3:
…......
break;
}SolutionFirst solution to this problem is copy the code of case 3 and put it in the if block of case 1. Example
case 1: …........if ( expression )break; But the problem with the above solution is that it makes code redundant. Second solution is to create a function and put the code in that and then execute the code.
case 1: …........if ( expression )
Case3Code();break;
function Case3Code()
{
….
}The problem with this solution is that I have to create one Extra function which is not needed. Third solution is to make use of Go To in switch..caseblock.
switch(MyVariable)
{
case 1:
…........
if ( expression )goto case 3:
break;
case 2:
…..
break;
case 3:
…......
break;
}So Go to in Switch..Case allows me to do the thing easily and in a maintainable way. |