HPlogo HP C/HP-UX Reference Manual: Version A.05.55.02 > Chapter 6 Statements

switch

» 

Technical documentation

Complete book in PDF

 » Table of Contents

 » Index

Syntax

switch ( exp )
{
  case const_exp : [statement]...
[case const_exp : [statement]...]
[default : [statement]...]

}

Arguments

exp

The integer expression that the switch statement evaluates and then compares to the values in all the cases.

const_exp

An integer expression to which exp is compared. If const_exp matches exp, the accompanying statement is executed.

statement

Zero or more simple statements. (If there is more than one simple statement, you do not need to enclose the statements in braces.)

Description

The switch statement is a conditional branching statement that selects among several statements based on constant values.

The expression immediately after the switch keyword must be enclosed in parentheses and must be an integral expression.

The expressions following the case keywords must be integral constant expressions; that is, they may not contain variables.

An important feature of the switch statement is that program flow continues from the selected case label until another control-flow statement is encountered or the end of the switch statement is reached. That is, the compiler executes any statements following the selected case label until a break, goto, or return statement appears. The break statement explicitly exits the switch construct, passing control to the statement following the switch statement. Since this is usually what you want, you should almost always include a break statement at the end of the statement list following each case label.

The following print_error() function, for example, prints an error message based on an error code passed to it.

/* Prints error message based on error_code.
* Function is declared with void because it doesn't
* return anything.
*/
#include <stdio.h>
#define ERR_INPUT_VAL 1
#define ERR_OPERAND 2
#define ERR_OPERATOR 3
#define ERR_TYPE 4
void print_error(int error_code)
{
switch (error_code) {
case ERR_INPUT_VAL:
printf("Error: Illegal input value.\n");
break;
case ERR_OPERAND:
printf("Error: Illegal operand.\n");
break;
case ERR_OPERATOR:
printf("Error: Unknown operator.\n");
break;
case ERR_TYPE:
printf("Error: Incompatible data.\n");
break;
default: printf("Error: Unknown error code %d\n",
error_code);
break;
}
}

The break statements are necessary to prevent the function from printing more than one error message. The last break after the default case is not really necessary, but it is a good idea to include it anyway for the sake of consistency.

Evaluation of switch Statement

The switch expression is evaluated; if it matches one of the case labels, program flow continues with the statement that follows the matching case label. If none of the case labels match the switch expression, program flow continues at the default label, if it exists. (The default label need not be the last label, though it is good style to put it last.) No two case labels may have the same value.

Associating Statements with Multiple case Values

Sometimes you want to associate a group of statements with more than one case value. To obtain this behavior, you can enter consecutive case labels. The following function, for instance, returns 1 if the argument is a punctuation character, or 0 if it is anything else.

/* This function returns 1 if the argument is a
 * punctuation character. Otherwise, it returns 0.
 */
is_punc(char arg)
{
    switch (arg) {
        case '.':
        case ',':
        case ':':
        case ';':
        case '?':
        case '-':
        case '(':
        case ')':
        case '!':  return 1;
        default :  return 0;
    }
}

Example

/* Use the switch statement to decide which comment should be printed */
#include <stdio.h>
int main(void)
{
char answer, grade;
answer = 'y';
printf("\n\n");
while (answer == 'y' || answer == 'Y') {
printf("Enter student's grade: ");
fflush(stdin);
scanf("%c", &grade);
printf("\nComments: ");
switch (grade) {
case 'A':
case 'a':
printf("Excellent\n");
break;
case 'B':
case 'b':
printf("Good\n");
break;
case 'C':
case 'c':
printf("Average\n");
break;
case 'D':
case 'd':
printf("Poor\n");
break;
case 'E':
case 'e':
case 'F':
case 'f':
printf("Failure\n");
break;
default:
printf("Invalid grade\n");
break;
} /* end switch */
printf("\nAgain? ");
fflush(stdin);
scanf("%s", &answer);
}
}

If you execute this program, you get the following output:

Enter student's grade: B

Comments: Good

Again? y
Enter student's grade: C

Comments: Average

Again? n

© Hewlett-Packard Development Company, L.P.