switch Statement

The switch and case statements help control complex conditional and branching operations. The switch statement transfers control to a statement within its body.


switch ( expression )

case constant-expression1 : statement;
case constant-expression2 : statement;
case constant-expressionN : statement;

default : statement;


Control passes to the statement whose case constant-expression matches the value of switch ( expression ). The switch statement can include any number of case instances, but no two case constants within the same switch statement can have the same value. Execution of the statement body begins at the selected statement and proceeds until the end of the body or until a break statement transfers control out of the body.

You can use the break statement to end processing of a particular case within the switch statement and to branch to the end of the switch statement. Without break, the program continues to the next case, executing the statements until a break or the end of the statement is reached. In some situations, this continuation may be desirable.

The default statement is executed if no case constant-expression is equal to the value of switch ( expression ). If the default statement is omitted, and no case match is found, none of the statements in the switch body are executed. There can be at most one default statement. The default statement, if exists, MUST come at the end. Otherwise it may be executed before hitting conditions defined below it. A case or default label is allowed to appear only inside a switch statement.

The type of switch expression and case constant-expression can be any. The value of each case constant-expression must be unique within the statement body. Otherwise first-match will be used.


for( n = 0; n < 10; n++ )
printf("Current n = %f\n", n );

switch(n) {
case 0:
printf("The number is zero.\n");
case 3:
case 5:
case 7:
printf("n is a prime number\n");
case 2: printf("n is a prime number\n");
case 4:
case 6:
case 8:
printf("n is an even number\n");
case 1:
case 9:
printf("n is a perfect square\n");
printf("Only single-digit numbers are allowed\n");

More information can be found here: http://en.wikipedia.org/wiki/Switch_statement