The switch statement

The switch statement


Content


1. What use of the operator “switch” in the program?

The statement “switch” provides multidirectional branching in the program. This statement allows select the choice of the several alternative cases of program executing. In the several cases, the “switch” statement can have more efficiency, than using the “if” statement.


2. What is the general view of “switch” statement?

The general vies of “switch” statement is following:

switch (expression)
{
   case constant1:
       statements1;
   break;
   case constant2:
       statements2;
   break;

   ...

   case constantN:
       statementsN;
   break;

   ...

   default:
       statements;
   break;
}

where

expression – the given expression of integer type, enumeration type or string type;

constant1, constant2, … constantN – the constants of the selection. The type of constants must be compatible with the type of expression. The constants must not have the same values;

statements1, statements2, …, statementsN, statements – the sequence of statements, that are executed in the case, if the value of constant coincides with the expression.

If any constant doesn’t coincide with expression, then the statements, that follow after “default” word, are executed.


3. What means the default section in the switch statement?

Statements, that follow after default word, are executed in that case, when the expression value doesn’t coincide to any constant. Section default is not mandatory.

If the word default is missing in the switch statement and a constant value is not equal the expression value, then no action is taken.


4. An example of using the switch statement without using the default section.

The integer n is given, that specifies the number of the day of week from 1 to 7. By specified number n display the name of corresponding day of week.

The code snippet that solves this task using the switch statement:

...
int n;

n = 7;

switch (n)
{
    case 1: label1.Text = "Monday";
    break;
    case 2: label1.Text = "Tuesday";
    break;
    case 3: label1.Text = "Wednesday";
    break;
    case 4: label1.Text = "Thursday ";
    break;
    case 5: label1.Text = "Friday";
    break;
    case 6: label1.Text = "Saturday";
    break;
    case 7: label1.Text = "Sunday";
    break;
}

5. An example of using the switch statement using the default section.

Write a code fragment, which determines the number of days of the month using the number n of month. The number of month days is saved in the k variable.

...

int n, k;

...

switch (n)
{
    case 2:
        k = 28;
    break;
    case 4: case 6: case 9: case 11:
       k = 30;
    break;
    default:
       k = 31;
    break;
}

...