Last Updated on April 10, 2023 by Prepbytes
The switch statement in C language is a decision control statement that is typically used when the user must choose between multiple alternatives. A switch statement allows programmers to execute different blocks of code based on the value of a single variable or expression. It is a type of conditional statement that simplifies the task of writing nested if-else statements. This article will help you in gaining a better understanding of the switch case program in C.
What is the Switch Statement in C?
The switch statement in C evaluates an expression and compares it to one or more constant expressions, called cases. If the value of the expression matches a case, the statements following that case are executed until a break statement is encountered. The break statement is used to terminate the switch block and transfer control to the end of the block.
Syntax of Switch Statement in C
Here is the syntax of a switch statement in C:
switch () {
// Expression evaluates to a single value.
case : //Case is picked when expression gives Value1.
;
;
break;
case :
;
;
break;
.
. //So on.
default: // When value of expression didn't match any case
;
;
break;
}
How does Switch Statement in C Works?
Let’s see how the switch statement in C works step by step:
- Step – 1 The switch statement evaluates an expression, which can be any scalar value, such as an integer or character.
- Step – 2 The expression is compared to the constant expressions, called cases, in the switch statement. Each case specifies a value that the expression might equal.
- Step – 3 If the value of the expression matches a case, the statements following that case are executed until a break statement is encountered. If there is no matching case, the program jumps to the default case, if it exists.
- Step – 4 The break statement is used to exit the switch statement and transfer control to the end of the switch block. If a break statement is not used, the program will continue executing the statements in the following cases, whether or not they match the value of the expression.
- Step – 5 If the default case is used, it will be executed if none of the other cases match the value of the expression. The default case is optional.
- Step – 6 Once the switch statement is completed, the program continues executing the statements following the switch block.
Flow Chart of Switch Case Program in C
Here is a flowchart of a basic switch case program in C.
Rules of Switch Case Statement in C
Here are some important rules to keep in mind when writing a switch case program in C.
- Rule: 1 The switch expression must be of integer or character type, or an enumerated type. Floating point types, pointers, and other non-integral types are not allowed.
- Rule: 2 Each case label must be a constant expression of the same type as the switch expression.
- Rule: 3 The case labels must be unique within a switch statement.
- A default label is optional, but if present, it must appear at the end of the switch statement.
- Rule: 4 The statements within each case label must be terminated with a break statement unless the case is intentionally fall-through to the next case label.
- Rule: 5 A switch statement can be nested inside another switch statement or any other control structure.
- Rule: 6 The switch expression is evaluated only once at the beginning of the switch statement, and its value is used to determine which case label to execute.
- Rule: 7 If the switch expression does not match any of the case labels, the default label (if present) is executed. If there is no default label, no statements within the switch statement are executed.
- Rule: 8 The case labels must be compile-time constants, meaning they must be known at the time of compilation. This means that variables cannot be used as case labels.
- Rule: 9 The case labels must not overlap. For example, you cannot have two case labels with the same value.
Examples
Now let’s go through some examples of the switch case program in C to deepen our understanding of switch statements.
Switch Case Program in C Showing Working of Basic Calculator
This is a classic use case of a switch we have in front of us. This is the kind of scenario where Switch works best. And here’s how we can implement this.
#include <stdio.h> int main() { char operator; double num1, num2, result; scanf("%c", &operator); scanf("%lf %lf", &num1, &num2); switch (operator) { case '+': result = num1 + num2; printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result); break; case '-': result = num1 - num2; printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result); break; case '*': result = num1 * num2; printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result); break; case '/': if (num2 == 0) { printf("Error: division by zero!\n"); } else { result = num1 / num2; printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result); } break; default: printf("Invalid operator!\n"); } return 0; }
Input:
+
23.3 20.7
Output:
23.30 + 20.70 = 44.00
Explanation: This program prompts the user to enter an arithmetic operator (+, -, *, /) and two numbers, and then performs the appropriate calculation using a switch statement. The switch statement compares the operator to each case label and computes the result accordingly.
Nested Switch Program in C
The switch statement, like any other if, else, etc., allows nesting. It means a switch case program in C can have another switch inside. To better comprehend it, let’s consider a simple example.
#include <stdio.h> int main() { int month, year; scanf("%d", &month); scanf("%d", &year); switch (month) { case 1: printf("January %d has 31 days.\n", year); break; case 2: switch (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { case 1: printf("February %d has 29 days.\n", year); break; case 0: printf("February %d has 28 days.\n", year); break; } break; case 3: printf("March %d has 31 days.\n", year); break; case 4: printf("April %d has 30 days.\n", year); break; case 5: printf("May %d has 31 days.\n", year); break; case 6: printf("June %d has 30 days.\n", year); break; case 7: printf("July %d has 31 days.\n", year); break; case 8: printf("August %d has 31 days.\n", year); break; case 9: printf("September %d has 30 days.\n", year); break; case 10: printf("October %d has 31 days.\n", year); break; case 11: printf("November %d has 30 days.\n", year); break; case 12: printf("December %d has 31 days.\n", year); break; default: printf("Invalid month!\n"); } return 0; }
Input:
2 1996
Output:
February 1996 has 29 days.
Explanation: This program prompts the user to enter a month (1-12) and a year, and then uses nested switch statements to determine the number of days in that month. The outer switch statement compares the month to each case label and selects the appropriate inner switch statement. The inner switch statement calculates whether February has 28 or 29 days. If the user enters an invalid month, the default case is executed, which prints an error message. Finally, the program prints the number of days in the given month and year.
Disadvantages of Implementing Switch Case Program in C
While the switch statement is a powerful tool for branching control flow based on a given expression, there are some disadvantages to implementing a switch case program in C:
- Limited Expression Types: The switch statement can only be used with expressions that evaluate integer or character types. This means that other data types, such as floating-point numbers, cannot be used in a switch statement.
- Limited Cases: The number of cases that can be used in a switch case program in C is limited by the range of the expression. For example, if the expression is an integer, it can only be used with a limited number of cases, which may not be sufficient for more complex branching logic.
- Lack of Flexibility: The switch statement is not as flexible as other branching structures, such as if-else statements. It can only compare the expression with fixed values and does not allow for more complex comparisons or conditions.
- Limited Fall-Through: In a switch statement, fall-through behavior can only be achieved by omitting the break statement, which can lead to unintended and difficult-to-debug errors.
- Maintenance Challenges: As the number of cases in a switch statement increases, it can become difficult to maintain and understand the code. It can be hard to identify which case statements are related and which are not, leading to code that is difficult to modify or update.
Conclusion
In conclusion, the switch statement is a powerful control flow statement in C that can simplify and improve the efficiency of code that needs to execute different actions based on the value of a variable. Although it has some limitations and drawbacks, it remains a popular and useful tool for many programming tasks.
FAQs
Here are some frequently asked questions on the switch case program in C.
Q1: Can we use variables as cases in a switch statement in C?
Ans: No, variables cannot be used as cases in a switch program in C. Only constants or literals can be used as cases.
Q2: Can we use floating-point numbers in a switch statement in C?
Ans: No, floating-point numbers cannot be used in a switch statement in C. Only integers or character types are allowed.
Q3: Can we use switch statements for string comparison in C?
Ans: No, switch statements cannot be used for string comparison in C. Instead, we need to use string functions like strcmp() to compare strings.
Q4: What is the purpose of the default case in a switch case program in C?
Ans: The purpose of the default case in a switch case program in C is to provide a block of code to be executed when none of the other cases match the value of the expression.
Q5: What is a fall-through case in a switch statement in C?
Ans: A fall-through case in a switch statement in C is a case that does not have a break statement at the end of its code block. This causes the code to "fall through" and execute the code for the next case, even if the value does not match.
Q6: Can we use switch statements with boolean expressions in C?
Ans: No, switch statements cannot be used with boolean expressions in C. Only integer or character types are allowed.
Q7: Can we use a switch statement without a default case in C?
Ans: Yes, it is possible to use a switch statement without a default.