Curriculum
A switch statement in C allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
switchswitch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// Additional cases...
default:
// Code to execute if expression doesn't match any case
}
switch Statements for Structured Decision-MakingImagine you’re building a menu-driven application where the main menu directs to submenus based on the user’s choice. Each submenu then presents further options. Instead of nesting switch statements, you structure the decision-making process across different functions or blocks of code.
#include <stdio.h>
void displayMainMenu() {
printf("Main Menu:n");
printf("1. Food Menun");
printf("2. Drink Menun");
printf("Enter your choice: ");
}
void displayFoodMenu() {
printf("Food Menu:n");
printf("1. Pizzan");
printf("2. Burgern");
// Additional food items...
}
void displayDrinkMenu() {
printf("Drink Menu:n");
printf("1. Watern");
printf("2. Sodan");
// Additional drink items...
}
void handleMainMenuChoice(int choice) {
switch (choice) {
case 1:
displayFoodMenu();
break;
case 2:
displayDrinkMenu();
break;
default:
printf("Invalid choice.n");
}
}
void handleFoodMenuChoice(int choice) {
// Implement similar logic for food menu choices
}
void handleDrinkMenuChoice(int choice) {
// Implement similar logic for drink menu choices
}
int getUserChoice() {
int choice;
scanf("%d", &choice);
return choice;
}
int main() {
int mainMenuChoice;
displayMainMenu();
mainMenuChoice = getUserChoice();
handleMainMenuChoice(mainMenuChoice);
// Based on the choice, you might want to call either
// handleFoodMenuChoice or handleDrinkMenuChoice next,
// possibly after displaying the corresponding menu and getting user input.
return 0;
}
if, switch, or any combination, deep nesting can make your code harder to follow. Strive for a flat structure.switch statements.case in your switch statement is clear and serves a single, concise purpose.This tutorial demonstrates how to structure your code when dealing with complex decision-making scenarios, providing a clean and maintainable approach without resorting to nested switch statements.