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.
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
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;
}
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.
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
What is the purpose of using a switch statement?
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.
Can the switch expression be a function call?
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.
Can a switch case be empty?
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.
Is it possible to use switch statements with char types?
Yes, switch statements can handle char types. Each case label can be a specific character, which is useful for handling different character inputs.
Can a switch statement be used with bitwise operations?
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.
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.