Switch Statements:

A switch statement is used as a control flow statement found in many programming languages. It provides a way to select and execute different code blocks based on the value of a given expression.


The switch statement matches the value with the expression provided in the parentheses and executes a block of code. It is like if statement. It can be used as an alternative of if statement.

Syntax:

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

Note: Do not forget to put break after every case.


Description:

  1. The switch statement begins with the keyword switch, followed by an expression enclosed in parentheses. This expression is often referred as the "selector" or "switch variable.".

  2. After the opening curly brace. you define individual cases using the case keyword, followed by a constant value or expression that represents a specific case to be matched.

  3. Each case block code consists of one or more statements that will be executed if the corresponding case matches with the value of the selector expression. The statements within each case are indented to make it readable.

  4. At the end of each case, it is essential to include the break statement to exit the switch block. Without the break statement, execution will continue to the next case, which may not be the desired behavior.

  5. Optionally, we can include a default case, which is executed when none of the previous cases match the value of the selector expression. It acts as a default fallback option when no specific case matches.

  6. The closing curly brace marks the end of the switch statement.

switch.c
#include <stdio.h>

int main() {
  int num = 19;
      
  switch (num) {
    case 1:
      printf("Number is 1.\n");
      break;
    case 2:
      printf("Number is 2.\n");
      break;
    default:
      printf("Number is neither 1 nor 2.\n");
  }
      
    return 0;
}

Note: Default case is optional. It is executed when no case is executed. There is no need to add a break after the default case.