4.1 - Using switches

The switch
statement provides a control structure that allows you to execute different parts of code based on the value of a variable. This can be particularly useful for handling multiple conditions that would otherwise require a complex series of if
statements.
Syntax of the switch
Statement
The general syntax of a switch
statement is as follows:
switch (expression) {
case constant1:
// Code to be executed if expression equals constant1
break;
case constant2:
// Code to be executed if expression equals constant2
break;
// You can have any number of case statements.
default:
// Code to be executed if expression does not match any case
}
Key Components
-
Expression: The expression inside the
switch
parentheses is evaluated once. The result is compared with the values of eachcase
. -
Case Labels: Each
case
represents a constant value. If the value of the expression matches acase
, the corresponding block of code is executed. -
Break Statement: The
break
statement is used to terminate acase
block. Ifbreak
is omitted, the execution will continue to the nextcase
, which is known as “fall-through”. -
Default Case: The
default
case is optional and acts as a catch-all. It executes if none of the specifiedcase
values match the expression.
Example of a Switch Statement
Here’s a simple example that demonstrates the use of a switch
statement:
#include <stdio.h>
int main() {
int day;
printf("Enter a day number (1-7): ");
scanf("%d", &day);
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day number\n");
break;
}
return 0;
}
Explanation of the Example
-
Input: The user is prompted to enter a number corresponding to a day of the week (1 for Monday, 2 for Tuesday, etc.).
-
Switch Evaluation: The
switch
statement evaluates the value ofday
. -
Case Execution: Depending on the entered number, the corresponding
case
block is executed. If the user enters a number not between 1 and 7, thedefault
block is executed, indicating an invalid input.
Important Notes
- Fall-Through Behavior: If you want multiple cases to execute the same block of code, you can omit the
break
statement between them:
switch (value) {
case 1:
case 2:
case 3:
printf("Value is between 1 and 3\n");
break;
case 4:
printf("Value is 4\n");
break;
default:
printf("Value is not between 1 and 4\n");
}
In this example, if value
is 1, 2, or 3, the same message will be printed.
-
Type of Expression: The expression in a
switch
statement must evaluate to an integer or an enumeration type. Floating-point values or strings cannot be used directly inswitch
. -
Efficiency:
switch
statements can be more efficient than multipleif-else
statements, especially when there are many conditions to evaluate. The compiler can optimize theswitch
for performance. -
Constant Values: The values used in the
case
labels must be constant expressions. This means they cannot be variables or results of computations. -
Nesting:
switch
statements can be nested inside otherswitch
statements or control structures, but this can make code more complex and harder to read.
Best Practices
- Use
default
: Always consider including adefault
case to handle unexpected values. - Avoid Fall-Through: Unless intentional, always include a
break
statement after eachcase
to avoid unintended execution of subsequent cases. - Readability: Keep the
switch
statements simple and readable. If you find yourself with many cases, consider if there’s a more efficient way to structure your logic, perhaps through arrays or lookup tables.
Summary
The
switch
statement is a powerful tool for controlling the flow of a program based on variable values.
Understanding
switch
syntax and behavior can greatly enhance your programming efficiency and make your code cleaner and more understandable.