The switch statement has the general syntax
switch (sw_exp) {
  case case_exp: case_statement
  [default: def_statement]
and allows for the transfer of control to one of several case-labeled statements, depending on the value of sw_exp (which must be of integral type).

Any case_statement can be labeled by one or more case labels. The case_exp of each case label must evaluate to a constant integer which is unique within it's enclosing switch statement.

There can also be at most one default label.

After evaluating sw_exp, the case_exp are checked for a match. If a match is found, control passes to the case_statement with the matching case label.

If no match is found and there is a default label, control passes to def_statement. Otherwise none of the statements in the switch is executed.

Program execution is not affected when case and default labels are encountered. Control simply passes through the labels to the following statement.

To stop execution at the end of a group of statements for a particular case, use the break statement.


string s = "Hello World";
int vowels = 0, others = 0;
for (int i = 0; s[i]; ++i)
    switch (toupper(s[i])) {
      case 'A':
      case 'E':
      case 'I':
      case 'O':
      case 'U': ++vowels;
      default: ++others;
printf("There are %d vowels in '%s'\n", vowels, s);

Index Copyright © 2005 CadSoft Computer GmbH