switch, case, default Keywords

Keyword Index

Branches control.

switch causes control to branch to one of a list of possible statements in the block of statements. The syntax is

switch (expression) statement
The statement statement is typically a compound statement (i.e. a block of statements enclosed in braces). The branched-to statement is determined by evaluating expression, which must return an integral type. The list of possible branch points within statement is determined by preceding substatements with
case constant-expression :
where constant-expression must be an int and must be unique.

Once a value is computed for expression, the list of possible constant-expression values determined from all case statements is searched for a match. If a match is found, execution continues after the matching case statement and continues until a break statement is encountered or the end of statement is reached. If a match is not found and this statement prefix is found within statement,
default :
execution continues at this point. Otherwise, statement is skipped entirely. For example,
switch (operand)
  {
    case MULTIPLY:
      x *= y; break;
    case DIVIDE:
      x /= y; break;
    case ADD:
      x += y; break;
    case SUBTRACT:
      x -= y; break;
    case INCREMENT2:
      x++;
    case INCREMENT1:
      x++; break;
    case EXPONENT:
    case ROOT:
    case MOD:
      printf ("Not implemented!\n");
      break;
    default:
      printf("Bug!\n");
      exit(1);
  }
See also break.

Note: GNU C extends the case keyword to allow case ranges.