Switch and case in c programming

23 Oct 2023 Balmiki Mandal 0 C Programming

Understanding Switch and Case Statements in C Programming

The switch statement in C programming is a control flow statement that allows you to execute a different block of code based on the value of a variable. The switch statement works by comparing the value of the variable to a list of cases. If the value of the variable matches one of the cases, the corresponding block of code is executed. If the value of the variable does not match any of the cases, the default block of code is executed.

Syntax for the switch statement is as follows:

C program
switch (variable) {
  case value1:
    // Code to be executed if the value of the variable is equal to value1
    break;
  case value2:
    // Code to be executed if the value of the variable is equal to value2
    break;
  ...
  default:
    // Code to be executed if the value of the variable does not match any of the cases
    break;
}

The break statement is used to exit the switch statement. If you do not include a break statement at the end of each case, the code in the next case will also be executed.

 How to use the switch statement:

C programming
int num = 10;

switch (num) {
  case 1:
    printf("The number is one.\n");
    break;
  case 2:
    printf("The number is two.\n");
    break;
  case 3:
    printf("The number is three.\n");
    break;
  default:
    printf("The number is not one, two, or three.\n");
    break;
}

Output:

The number is ten.

The switch statement can be used to simplify complex if-else statements. For example, the following code is equivalent to the previous code:

C programming
int num = 10;

if (num == 1) {
  printf("The number is one.\n");
} else if (num == 2) {
  printf("The number is two.\n");
} else if (num == 3) {
  printf("The number is three.\n");
} else {
  printf("The number is not one, two, or three.\n");
}

The switch statement is a powerful tool for controlling the flow of your code. It can be used to simplify complex if-else statements and make your code more readable.

Some Additional things to keep in mind when using the switch statement:

 

  • The switch statement can only be used with integral data types, such as int, char, and enum.
  • The cases in the switch statement must be unique.
  • The default case is optional.
  • You can use multiple break statements to exit the switch statement from anywhere in the code.
  • You can also use the fallthrough keyword to execute the code in the next case without exiting the switch statement.

 

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.