C documentation V1 Help

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:

  1. We declare a variable choice to store the user's input.

  2. The printf function prompts the user to enter a choice, and scanf reads the input into the choice variable.

  3. The switch statement is used to check the value of choice against different cases.

  4. Each case represents a possible value of choice. If a match is found, the corresponding code block is executed.

  5. The break statement is used to exit the switch statement after a case is executed.

  6. The default case is optional and executed if none of the case values matches the value of choice.

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 a switch statement should end with a break 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!

Last modified: 25 February 2024