The switch Statement


The switch statement has the following form.

switch (expression)
{
 case constant1:
  statement sequence
  break;

 case constant2:
  statement sequence
  break;
 ...
 default:
  statement sequence
  break;
}

The switch expression must be of integer type or of type string. Floating point expressions are not permitted. No two cases can have the same value. The default case is executed when no case constants match the switch expression. The default case is optional and if not present, no action is taken when all matches fail. When a match is made, the corresponding statement sequence is executed until a break is encountered. When a break is encountered, the entire switch statement is exited.

It is an error for the statement sequence of a case to continue onto the next case without an intervening break statement (or some other statement such as a goto). Despite this, several cases may be attached to the same code, as shown below.

int i;
...
switch(i)
{
 case 1:
 case 2:
 case 3:
   i++;
   break;

 case 4:
   i += 2;
   break;

 default
   i--;
   break;
}