Course Content
Programming in C
About Lesson

The switch statement is a multi-way decision that matches the value of an expression against one of a number of constant integer values and branches accordingly.

switch (expression) {
  case const-expr: statements
  case const-expr: statements
  default: statements
}

Each case is labelled by some integer-valued constants or constant expressions. Execution starts at the case that matches the switch expression. A default, which is optional, gets executed if none of the other cases are matched. Cases and default can occur in any order.

One the control reaches a case statement, all the statements following that case (including cases that follow) will be executed. To prevent this from happening, we use a break statement at the end of each case. The break statement causes immediate exit from the switch (We could also use break statement inside a loop to exit the loop).

switch (c) {
  case '0': case '1': case '2': case '3': case '4':
  case '5': case '6': case '7': case '8': case '9':
    digits++;
    break;
  case ' ':
  case 't':
    spaces++;
    break;
  default:
    others++;
    break;
}
Scroll to Top