contents   index   previous   next



switch, case, and default

 

The switch statement makes a decision based on the value of a variable or statement. The switch statement follows the following format:

 

switch( switch_variable )

{

case value1:

   statement1

   break;

case value2:

   statement2

   break;

 

...

 

default: 

   default_statement

}

 

The variable switch_variable is evaluated, and then it is compared to all of the values in the case statements (value1, value2,  . . . , default) until a match is found. The statement or statements following the matched case are executed until the end of the switch block is reached or until a break statement exits the switch block. If no match is found, the default statement is executed, if there is one.

 

For example, suppose you had a series of account numbers, each beginning with a letter that determines what type of account it is. You could use a switch statement to carry out actions depending on that first letter. The same task could be accomplished with a series of nested if statements, but they require much more typing and are harder to read.

 

switch ( key[0] )

{

case 'A':

   Screen.write("A"); //handle 'A' accounts...

   break;

case 'B':

   Screen.write("B"); //handle 'B' accounts...

   break;

case 'C':

   Screen.write("C"); //handle 'C' accounts...

   break;

default:

   Screen.write("Invalid account number.\n");

   break;

}

 

A common mistake is to omit a break statement to end each case. In the preceding example, if the break statement after the Screen.write("B") statement were omitted, the computer would print both "B" and "C", since the interpreter executes commands until a break statement is encountered.

 

Normally, if a switch and series of case statements reference array variables, then a comparison is performed whether or not the reference the same array data. But if either the switch variable or one of the case values is a literal string, then the comparison of the strings is done using the values of the strings in a Clib.strcmp() type of comparison.

 


goto and labels