HP C A.06.05 Reference Manual

Statements
switch
Chapter 6 179
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.