Intoduction to Computer Science - C++

Alternating program flow with a Switch Case

Switch Case statements are like "if" statements that have been optimised for the situation where the programmer wants to test the same expression for many possible values. The syntax is the following (where var and var_1 etc. are integers or characters):
switch(var)  //equivalent to "if var "
{
   case var_1:  //equivalent to "==  var_1;" then do the folowing statements separated by ';' 
     cout<<var_1;
     break;   //leave the switch
   case var_2:   //equivalent to "==  var_2;"

     cout<<var_2;
     break;
              //etc.
   case var_n:
     cout<<var_n;
     break;
   default:   //if nothing else matches do this
     //do the folowing statements separated by ';' 
     cout<<"No action taken";
}



Here is the basic structure of all case switches:

 switch ( integer )

{
case 1: 
        statement;
        statement;
        statement;
        break;
case 2: 
        statement;
        statement;
        statement;
        break;
case 3: 
        statement;
        statement;
        statement;
        break;
etc.
etc.

default:
        statement;
        statement;
}

        Any expression can go inside the switch. The computer goes through the cases in order looking for a case that returns TRUE for the comparison ((expression from switch) == (value from case)).

If the computer reaches a case which matches, it performs the set of statements beneath it until it finds a break statement. BEWARE if you forget to put a break statement at the end of your case the computer will continue with the statements under the next case statement. This is called "falling through" the cases. Usually you don't want to have this happen, so be sure to include a break after each case. But, if falling through is used properly, it can be a feature - not a bug.

The programmer can also use a default case. This case is put at the end of all the cases and it will always match in cases where no other case matched.

Let's see an example:


int lucky_number;
cout<<"Guess the Integer:";
cin>>lucky_number;
switch(lucky_number)
{
 case -1:
 case -2:
 case -3:   //for all these cases do this
   cout<< "Don't be so negative!\n";
   break;   //the break tells me to leave the switch
 case 0:
   cout<<"You're a 0!\n";
   break;   
 case 1:
   cout<<"You're Number 1!\n";
   break;
 case 2:
   cout<<"Two's Company!\n";
   break;
 case 3:
   cout<<"Three's a crowd!\n";
   break;
 case 4:
   cout<<"Why have you 4saken me?\n";
   break;
 case 5:
   cout<<"High 5!\n";
   break;
 case 6:
   cout<<"Pick up Sticks!\n";
   break;
 case 7:
   cout<<"That's MY Lucky Number!\n";
   break;
 case 8:
   cout<<"Crazy Eights!\n";
   break;
 case 9:
   cout<<"Only cats have 9 lives!\n";
   break;
}

© Nachum Danzig September 2003 - January 2006