Pranay Rana: Go To with Switch..Case

Saturday, February 12, 2011

Go To with Switch..Case

Go To
Allows us to jump unconditionally when require and its 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.

Problem
In my application I reach stage where I have to execute code of the Case 1 of the Switch..Case and if the the some condition satisfy I have to execute the code of Case 3 of Switch..Case.

Example
Switch(myvariable)
{
    case 1:
    //statements
   …........
   if ( expression )
    execute case 3:
   break;
  
  case 2:
 …..
 break;
 
 case 3:
 …......
 break; 
}

Solution
First solution to this problem is copy the code of case 3 and put it in the if block of case 1
Example
case 1:
    //statements
   …........
   if ( expression )
     //code of case 3
   break;
But the problem with above solution is it make code redundant.

Second solution is to create function and put the code in that and than execute the code.
case 1:
    //statements
   …........
   if ( expression )
     Case3Code();
   break;

function Case3Code()
{
 ….
}
The problem with this solution is that I have to create one Extra function which is no needed.

Third solution is to make use of Go To in switch..case block.
switch(MyVariable)
{
 case 1:
 //statements
   …........
 if ( expression )
    goto case 3:
 break;
  
 case 2:
 …..
 break;
 
 case 3:
 …......
 break; 
}
so Go to in Switch..Case allow me to do the thing easy and the maintainable way.

2 comments:

  1. 太宰治や武田信玄や県内最大級で、国の史跡にも指定されている銚子塚古墳や丸山塚古墳など歴史・文化溢れる甲府で知的な出会いしてみませんか?

    ReplyDelete
  2. 松江周辺には神話がもとになった縁結びスポットが沢山あります!そうなれば。。出会い…”縁”を求めている人、結ばれた縁をさらに深めたい人にもおすすめの場所なんです!神に祝福される様な出会いをして下さい!

    ReplyDelete