Switch Statement

The Switch statement it is used if you want to select one of many blocks of code to be executed .

Basic structure

switch (expression)

{

case label1:

code to be executed if expression = label1;

break;

case label2:

code to be executed if expression = label2;

break;

default:

code to be executed

if expression is different

from both label1 and label2;

}

The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed.

First we have a single expression (most often a variable), that is evaluated once.

The value of the expression is then compared with the values for each case in the structure.

If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if none of the cases are true.

Also default statement it is optional . If none of the cases are true and there is no default statement no action will take place.

admin – Thu, 2005 – 07 – 07 12:14