The switch construction is provided to make life as a programmer easier. It does not do anything which we can't do using multiple if constructions, but it is intended to make it quick and easy to select one option from a number of possible ones.
We will find that this is the case with a lot of the program constructions offered by C. In theory you can make do with just one loop construction and then alter how you use it depending to your requirements, but in C you have three different loop constructions which you can use for different things.
switch ( control variable ) { case constant1 : /* code for this value */ break ; case constant2 : case constant3 : /* code for this value */ break ; default : /* code for no matches */ break ; }
The syntax for the switch is given above.. The control variable has a particular value. The switch construction causes the program to obey the case which has a matching value. Note that the same case is obeyed for two possible values (constant2 and constant3) of the control variable. Note also that you are allowed a default case, which is obeyed if the control variable does not match any of the cases. The break keyword is particularly important, as it stops the execution of a case and takes execution to the statement after the switch. The case constant values don't have to be in any particular order as the compiler will sort this out. (In fact the compiler just generates lots of "if" constructions - just like we would do if we didn't have the switch construction available)
Remember that the things which follow the case must be constants, you cannot put variables in these positions. I frequently use the switch construction to select command code from the user:
char ch ; /* get the command into character*/ /* variable ch */ switch ( ch ) { case 'S' : case 's' : save_function () ; break ; case 'L' : case 'l' : load_function () ; break ; case 'Q' : case 'q' : quit_function () ; break ; default : bad_command () ; break ; }
The code above would provide the main menu decoding for the program. It calls a particular function depending on the key which the user presses. I have used the multiple case trick to allow me to handle upper or lower case commands easily.
On the right you can see a switch construction in a CPIC. The variable count is set to 3. It is then used to control a switch. When you run the program you will see that it executes the code which matches this value. When the code is complete it uses the break to signal when it has finished.