Switch Statement
The switch
statement in C provides a way to make multi-way decisions based on the value of an expression. It allows the program to choose a specific code block to execute from several alternatives. Let's explore the syntax and usage of the switch
statement.
Basic Syntax of Switch Statement
#include <stdio.h>
int main() {
int choice;
// Prompt the user to enter a choice
printf("Enter a choice (1, 2, or 3): ");
scanf("%d", &choice);
// Switch statement
switch (choice) {
case 1:
printf("You chose Option 1\n");
break;
case 2:
printf("You chose Option 2\n");
break;
case 3:
printf("You chose Option 3\n");
break;
default:
printf("Invalid choice\n");
}
return 0;
}
Explanation of the Program:
We declare a variable
choice
to store the user's input.The
printf
function prompts the user to enter a choice, andscanf
reads the input into thechoice
variable.The
switch
statement is used to check the value ofchoice
against different cases.Each
case
represents a possible value ofchoice
. If a match is found, the corresponding code block is executed.The
break
statement is used to exit theswitch
statement after a case is executed.The
default
case is optional and executed if none of thecase
values matches the value ofchoice
.
Handling Fall-Through
Unlike some other programming languages, C allows fall-through behavior between cases. If there is no break
statement, the control will fall through to the next case.
#include <stdio.h>
int main() {
int day = 3;
// Switch statement with fall-through
switch (day) {
case 1:
printf("Monday\n");
case 2:
printf("Tuesday\n");
case 3:
printf("Wednesday\n");
default:
printf("Unknown day\n");
}
return 0;
}
In this example, if day
is 3, the output will be:
Wednesday
Unknown day
Practical Tips
Each
case
in aswitch
statement should end with abreak
statement to avoid fall-through behavior unless intentional.Use the
default
case to handle unexpected or invalid values.
Understanding and effectively using the switch
statement enhances the flexibility of decision-making in C programs. If you have specific questions or if there are additional topics you'd like to explore, feel free to ask. Happy coding!
Was this helpful?