Switch Statement in C : Ensuring Cleaner & More Efficient Code

Updated on September 13, 2024

Article Outline

In C language, many decision control statements are used to decide the order of execution/flow of control in a program by making a decision based on a condition. The switch statement is a decision control statement in the C language. It is primarily used when the user has to decide between multiple alternatives.

What is the Switch Statement?

The switch statement is a control flow statement used in many programming languages. It executes different source code blocks based on the value of a variable or expression. It provides a way to simplify complex conditional logic that might otherwise require multiple if-else statements.

 

Also Read: Global Variable in C

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Syntax of Switch Statement

switch(expression) { case value1: statement_1; break; case value2: statement_2; break; . . . case value_n: statement_n; break; default: default_statement; }

How Does the C Switch Statement Work?

  • The expression inside the switch clause is evaluated as an integral constant.
  • Its result is then compared against the case value inside each case statement.
  • If the match is found in the switch cases, it will be executed until the break or end of the switch is encountered. This is a critical statement.

 

The following program demonstrates the switch statement in C language:

 

Program

#include <stdio.h>  int main(){ int day ;  printf("Enter a number any Integer number ") ; scanf("%d",&day) ;  switch(day){ case 1:  printf("Mondayn")  ; break ; case 2: printf("Tuesdayn")  ; break ;  case 3: printf("Wednesdayn")  ; break ; case 4: printf("Thursdayn")  ; break ; case 5: printf("Fridayn") ; break ; case 6: printf("Saturdayn") ; break ; case 7: printf("Sundayn") ; break ;   default : printf("Invalid Input Please enter a number between 1 and 7 n") ; } return 0 ; }

Output

Enter a number any Integer number 5 Friday

Flowchart of Switch Case in C

Flowchart of Switch Case in C

Rules of C switch  Statement

The switch statement is a control flow construct in C language that allows you to execute one block of source code for multiple options based on the value of a variable. We must follow some rules for using the switch statement in C.

  • In a switch statement, the “case value” must be of “char” and “int” type.
  • There can be one or N number of cases.
  • The values in the case must be unique.
  • In the Switch statement, the break statement is optional.
  • The default statement is also optional.

Program

#include<stdio.h> int main(){ int var = 1 ;   char ch = 'c' ;   switch(var){ case 1: printf("Case 1 is Matched") ; break  ; case 2: printf("Case 2 is Matched") ; break ; case 3: printf("Case 3 is Matched") ; break ; case 4: printf("Case 4 is Matched") ; break ; case 5: printf("Case 5 is Matched") ; break ;   case 6: printf("Case 6 is Matched") ; break ; case 7: printf("Case 7 is Matched") ;   break ; default : printf("This is a default case") ;     } switch(ch){   case 'a': printf("Character a is Matched") ; break ; case 'b' : printf("Character b is Matched") ; break ; case 'c' : printf("Character c is Matched") ; break ; case 'd' : printf("Character d is Matched") ; break ; case 'e' : printf("Character e is Matched") ; break ; case 'f' : printf("Character f is Matched") ; break ; case 'g' : printf("Characer g is Matched") ;   break ; default : printf("Character is not matched") ;   } return 0 ; }

Output

Case 1 is Matched Character c is Matched

Nested switch in C

The Switch statement supports nesting similarly to any programming language. This means we can write a switch inside another switch and keep doing it several times. Let’s see a simple example of understanding nesting in the switch in C language.   The following program demonstrates the Nesting switch in the C language

Program

#include <stdio.h>  int main() { int categoryChoice, itemChoice;  printf("Welcome to the Store Menu System!n"); printf("Categories:n"); printf("1. Electronicsn"); printf("2. Clothingn"); printf("3. Foodn"); printf("4. Exitn"); printf("Enter your category choice: "); scanf("%d", &categoryChoice); switch (categoryChoice) { case 1: // Electronics menu printf("Electronics Menu:n"); printf("1. Laptopn"); printf("2. Smartphonen"); printf("3. Headphonesn"); printf("Enter your item choice: "); scanf("%d", &itemChoice);  switch (itemChoice) { case 1: printf("You chose Laptop.n"); break; case 2: printf("You chose Smartphone.n"); break; case 3: printf("You chose Headphones.n"); break; default: printf("Invalid item choice in Electronics.n"); break; } break;  case 2: printf("Clothing Menu:n"); printf("1. T-shirtn"); printf("2. Jeansn"); printf("3. Jacketn"); printf("Enter your item choice: "); scanf("%d", &itemChoice);  switch (itemChoice) { case 1: printf("You chose T-shirt.n"); break; case 2: printf("You chose Jeans.n"); break; case 3: printf("You chose Jacket.n"); break; default: printf("Invalid item choice in Clothing.n"); break; } break;   case 3: printf("Food Menu:n"); printf("1. Pizzan"); printf("2. Burgern"); printf("3. Saladn"); printf("Enter your item choice: "); scanf("%d", &itemChoice);   switch (itemChoice) { case 1: printf("You chose Pizza.n"); break; case 2: printf("You chose Burger.n"); break; case 3: printf("You chose Salad.n"); break; default: printf("Invalid item choice in Food.n"); break; } break;   case 4: printf("Exiting the system. Have a nice day!n"); break;  default: printf("Invalid category choice.n"); break; }   return 0; }

 

Output

Welcome to the Store Menu System! Categories:
  1. Electronics
  2. Clothing
  3. Food
  4. Exit

 

Enter your category choice: 1 Electronics Menu:

  1. Laptop
  2. Smartphone
  3. Headphones

Enter your item choice: 1 You chose Laptop.

 

Also Read: Static Variable in C

Switch vs if else

In this table, we differentiate the switch and if-else statements in the following table:

 

Switch If-else
A switch statement has a default case to when an unexpected value gets from the user The final else block acts similarly to the default case in a switch.
Case labels must be of the same type as the expression being switched on Conditions can be of any boolean expression, not limited to a specific type.
This typically does not support ranges or multiple values in a single case It supports ranges and complex conditions, allowing greater flexibility.
The case labels are sensitive to type and value The conditions are sensitive to the boolean expression provided
The switch statements are more efficient with large numbers of cases due to internal optimizations This can handle ranges and complex boolean conditions

 

Also Read: goto Statement in C

Why Do We Need a C Switch Case?

The switch statement in C provides a clear and efficient way to handle multiple discrete values for single expressions, offering several key advantages over traditional if-else chains. Its primary benefit is improved readability, as it organizes source code by grouping related cases together.

 

It makes it easier to understand and manage when dealing with numeric-specific values. Overall, the switch statement is particularly valuable when handling multiple distinct values for a single variable efficiently and maintainable.

 

Let’s discuss some important points of the switch statement in C language:

 

  • Structured Control Flow: This provides a clear and organized way to handle multiple discrete values for a single expression.
  • Readability: This enhances readability by grouping related cases, making it easier to understand the logic.
  • Efficiency: The switch statement can be more efficient than if-else chains due to compiler optimizations like jump tables.

 

  • Default Case: This includes a default case to handle unexpected or unhandled values, ensuring robustness.

 

  • Error Handling and Debugging: This facilitates error handling and debugging by clearly separating cases and providing a default option.

 

  • Maintainability: It simplifies adding or modifying cases, making the source code easier to maintain than complex if-else structures.

 

Also Read: String Concatenation in C

Conclusion

The switch statement in C is a powerful tool for managing complex control flows involving multiple discrete values. Its structured approach enhances source code readability and maintainability by clearly grouping related cases and simplifying modifications. Due to compiler optimizations, the switch statement can be more efficient than a series of if-else statements, especially with many cases. The switch statement is best suited for scenarios where a fixed set of discrete values needs to be handled clearly and efficiently.

FAQs
The switch statement executes different source code blocks based on the value of a single expression. Compared to a series of if-else statements, it provides a more organized and readable way to handle multiple discrete values.
Yes, the switch expression can result from a function call if the function returns an integral type. This allows for more dynamic conditions in the switch statement.
Although the switch case can technically be empty, it is usually not recommended. An empty case label without associated source code or a break statement can lead to confusion and bugs. If no action is needed for a case, the consideration should add a comment to clarify the intention or handle it appropriately.
Yes, switch statements can handle char types. Each case label can be a specific character, which is useful for handling different character inputs.
Yes, a switch statement can handle values resulting from bitwise operations to ensure that the result of the bitwise operation matches one of the case labels.

Updated on September 13, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved