If you are bored with if-then-else, just switch
I am Jyotiprakash, a deeply driven computer systems engineer, software developer, teacher, and philosopher. With a decade of professional experience, I have contributed to various cutting-edge software products in network security, mobile apps, and healthcare software at renowned companies like Oracle, Yahoo, and Epic. My academic journey has taken me to prestigious institutions such as the University of Wisconsin-Madison and BITS Pilani in India, where I consistently ranked among the top of my class.
At my core, I am a computer enthusiast with a profound interest in understanding the intricacies of computer programming. My skills are not limited to application programming in Java; I have also delved deeply into computer hardware, learning about various architectures, low-level assembly programming, Linux kernel implementation, and writing device drivers. The contributions of Linus Torvalds, Ken Thompson, and Dennis Ritchie—who revolutionized the computer industry—inspire me. I believe that real contributions to computer science are made by mastering all levels of abstraction and understanding systems inside out.
In addition to my professional pursuits, I am passionate about teaching and sharing knowledge. I have spent two years as a teaching assistant at UW Madison, where I taught complex concepts in operating systems, computer graphics, and data structures to both graduate and undergraduate students. Currently, I am an assistant professor at KIIT, Bhubaneswar, where I continue to teach computer science to undergraduate and graduate students. I am also working on writing a few free books on systems programming, as I believe in freely sharing knowledge to empower others.
In C, the switch statement is used to perform different actions based on the value of an expression. It provides a convenient way to handle multiple conditions in a concise and readable manner. Here's a detailed explanation with a code sample:
#include <stdio.h>
int main() {
// Declare a variable
int choice;
// Prompt user for input
printf("Enter a number (1-3): ");
scanf("%d", &choice);
// Switch statement
switch (choice) {
// Case 1
case 1:
printf("You selected option 1.\n");
// Additional statements for case 1
break; // The 'break' statement is important to exit the switch block
// Case 2
case 2:
printf("You selected option 2.\n");
// Additional statements for case 2
break;
// Case 3
case 3:
printf("You selected option 3.\n");
// Additional statements for case 3
break;
// Default case (optional)
default:
printf("Invalid choice.\n");
// Additional statements for the default case
break;
}
return 0;
}
Explanation:
Declaration and Input: First, we declare an integer variable
choiceto store the user's input. We then prompt the user to enter a number (1-3) and store it in thechoicevariable usingscanf.Switch Statement: The
switchstatement is used to evaluate the value of thechoicevariable. The value inside the parentheses ofswitchis the expression that is being tested.Cases: Each
caserepresents a possible value of the expression. In this example, we have cases for 1, 2, and 3. If the value ofchoicematches any of these cases, the corresponding block of code is executed.Break Statement: After each case block, a
breakstatement is used to exit theswitchstatement. This is important because it prevents the code from falling through to the next case. Withoutbreak, all the subsequent cases would be executed until abreakis encountered.Default Case (Optional): The
defaultcase is optional and is executed if none of the cases match the value of the expression. It is like an "else" statement in anif-elsestructure.
The switch statement provides a clean and efficient way to handle multiple conditions based on the value of an expression. Each case block contains the code to be executed for a specific value, and the break statement ensures that only the relevant block is executed.
If you omit the break statement in a switch case, a phenomenon known as "fall-through" occurs. Fall-through means that control will "fall through" to the next case, and subsequent case blocks will be executed until a break statement is encountered or until the end of the switch statement. Here's an example with an explanation:
#include <stdio.h>
int main() {
int choice;
printf("Enter a number (1-3): ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You selected option 1.\n");
// No break here, so it falls through to the next case
case 2:
printf("You selected option 2.\n");
// No break here, so it falls through to the next case
case 3:
printf("You selected option 3.\n");
// No break here, so it continues to execute the next case
default:
printf("This is the default case.\n");
break;
}
return 0;
}
Explanation:
User Input and Switch Statement: The program prompts the user for input and uses a
switchstatement to evaluate the value ofchoice.Fall-Through: In each
caseblock, there is nobreakstatement. As a result, if the user enters, for example,1, the program will print "You selected option 1." and then continue to execute the code in the next case without checking its condition.Output: If the user enters
1, the output will be:You selected option 1. You selected option 2. You selected option 3. This is the default case.Default Case: The
defaultcase is executed because control falls through from the previous cases. If there were abreakafter each case, only the relevant block of code would be executed.
Using fall-through can be intentional in some cases when you want multiple cases to share the same code. However, it's important to use it judiciously and document it well, as it can make the code less readable and may lead to unexpected behavior if not handled carefully.
Cases can be combined in a switch statement by intentionally omitting the break statement between cases. This allows multiple cases to share the same block of code. Here's an example with a detailed explanation:
#include <stdio.h>
int main() {
int choice;
printf("Enter a number (1-3): ");
scanf("%d", &choice);
switch (choice) {
// Combining cases 1 and 2
case 1:
case 2:
printf("You selected option 1 or 2.\n");
// No break, so it falls through to the next case
case 3:
printf("You selected option 3.\n");
// No break here, so it continues to execute the next case
default:
printf("This is the default case.\n");
break;
}
return 0;
}
Explanation:
User Input and Switch Statement: The program prompts the user for input and uses a
switchstatement to evaluate the value ofchoice.Combining Cases 1 and 2: In this example, cases 1 and 2 are intentionally combined by omitting the
breakstatement after case 1. If the user enters either 1 or 2, the program will execute the code for both cases.Fall-Through: Since there is no
breakafter case 2, control falls through to the code for case 3.Output: If the user enters
1, the output will be:You selected option 1 or 2. You selected option 3. This is the default case.Default Case: The
defaultcase is executed if none of the specific cases match. Thebreakstatement at the end ensures that theswitchstatement is exited.
Combining cases can be useful when you want multiple cases to share the same code. However, it should be done intentionally and documented to make the code more readable and understandable. It's crucial to be aware of the fall-through behavior and use it only when it serves a specific purpose in your code.
The switch statement is designed to work with integral types, such as integers (int), characters (char), and enumerated types. The expression within the switch statement must evaluate to an integral value.
The following data types are generally allowed in a switch statement:
int and its variations (short int, long int, etc.):
int number; switch (number) { // cases... }char and its variations:
char letter; switch (letter) { // cases... }Enumeration types (enum):
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; enum Day today; switch (today) { // cases... }
It's important to note that the switch statement doesn't work with floating-point types, strings, or other non-integral types. If you need to perform a multi-way branch based on non-integral values, you would typically use a series of if-else statements or other control flow constructs.