A switch statement allows a single variable to be compared with
several possible constants. If the variable matches one of the
constants, then a execution jump is made to that point. A
constant can not appear more than once, and there can only be
one default expression.
Syntax:
switch ( variable )
{
case const:
statements...;
default:
statements...;
}
Examples:
switch(betty)
{
case 1:
printf("betty=1\n");
case 2:
printf("betty=2\n");
break;
case 3:
printf("betty=3\n");
break;
default:
printf("Not sure.\n");
}
If betty is 1, then two lines are printed: betty=1 and betty=2.
If betty is 2, then only one line is printed: betty=2. If
betty=3, then only one line is printed: betty=3. If betty does
not equal 1, 2, or 3, then "Not sure." is printed. |