Examples of switch statements
The following switch
statement contains several case
clauses
and one default
clause. Each clause contains a function
call and a break
statement. The break
statements
prevent control from passing down through each statement in the switch
body.
If the switch
expression evaluated to '/'
,
the switch statement would call the function divide
.
Control would then pass to the statement following the switch
body.
char key;
printf("Enter an arithmetic operator\n");
scanf("%c",&key);
switch (key)
{
case '+':
add();
break;
case '-':
subtract();
break;
case '*':
multiply();
break;
case '/':
divide();
break;
default:
printf("invalid key\n");
break;
}
If the switch expression matches a case expression, the statements
following the case expression are processed until a break
statement
is encountered or the end of the switch
body is reached.
In the following example, break
statements are not
present. If the value of text[i]
is equal to 'A'
,
all three counters are incremented. If the value of text[i]
is
equal to 'a'
, lettera
and total
are
increased. Only total
is increased if text[i]
is
not equal to 'A'
or 'a'
.
char text[100];
int capa, lettera, total;
// ...
for (i=0; i<sizeof(text); i++) {
switch (text[i])
{
case 'A':
capa++;
case 'a':
lettera++;
default:
total++;
}
}
The following switch
statement performs the same
statements for more than one case
label:
/**
** This example contains a switch statement that performs
** the same statement for more than one case label.
**/
#include <stdio.h>
int main(void)
{
int month;
/* Read in a month value */
printf("Enter month: ");
scanf("%d", &month);
/* Tell what season it falls into */
switch (month)
{
case 12:
case 1:
case 2:
printf("month %d is a winter month\n", month);
break;
case 3:
case 4:
case 5:
printf("month %d is a spring month\n", month);
break;
case 6:
case 7:
case 8:
printf("month %d is a summer month\n", month);
break;
case 9:
case 10:
case 11:
printf("month %d is a fall month\n", month);
break;
case 66:
case 99:
default:
printf("month %d is not a valid month\n", month);
}
return(0);
}
If the expression month
has the value 3
,
control passes to the statement:
printf("month %d is a spring month\n",
month);
The break
statement passes control to the statement
following the switch
body.
- CHECKOUT(*GENERAL) in the ILE C/C++ Compiler Reference
- Case and Default Labels
- The break statement