Make your own free website on Tripod.com

    Lesson 5: switch-case Statements

Prev || Home || Next

Switch case statements are a substitute for long if statements. The basic format for using switch case is outlined below.

Switch (expression or variable)       
{       
case variable equals this:        
do this;       
break;       
case variable equals this:        
do this;       
break;       
case variable equals this:       
do this;       
break;   
    ...       
default:       
do this   
}


The expression or variable has a value. The case says that if it has the value of whatever is after that cases then do whatever follows the colon. The break is used to break out of the case statements. Break is a keyword that breaks out of the code block, usually surrounded by braces, which it is in. In this case, break prevents the program from testing the next case statement also.

Switch case serves as a simple way to write long if statements. Often it can be used to process input from a user.

Below is a sample program, in which not all of the proper functions are actually declared, but which shows how one would use switch case in a program.

#include <iostream.h>   
#include <conio.h>   
int main()
{    
char input;   
cout<<"1. Play game";   
cout<<"2. Load game";   
cout<<"3. Play multiplayer";   
cout<<"4. Exit";   
cin>>input;   
switch (input)   
{   
case 1: playgame();
    break;   
case 2:
    loadgame();   
break;   
case 3:    //Note use of : not ;   
playmultiplayer();
    break;   
case 4:
return 0;
default:    
cout<<"Error, bad input, quitting";   
}
return 0;
}

This program will not compile yet, but it serves as a model (albeit simple) for processing input.

If you do not understand this then try mentally putting in if statements for the case statements. Note that using return in the middle of main will automatically end the program. Default simply skips out of the switch case construction and allows the program to terminate naturally. If you do not like that, then you can make a loop around the whole thing to have it wait for valid input. I know that some functions were not prototyped. You could easily make a few small functions if you wish to test the code.


Prev || Home || Next