The switch statement in C is a control flow statement that allows you to choose between multiple alternatives based on the value of a given expression. It provides a concise way to write multiple conditional statements that check a single variable against several different values.
Here’s the general syntax of a switch statement in C:
switch (expression) { case value1: // code to be executed if expression equals value1 break; case value2: // code to be executed if expression equals value2 break; case value3: // code to be executed if expression equals value3 break; // ... default: // code to be executed if expression doesn't match any of the cases above break; }
Here’s how a switch statement works:
- The expression is evaluated, and its value is compared to the values in each case.
- If a case value matches the expression value, the corresponding code block is executed. The code execution continues until it reaches a break statement or the end of the switch statement.
- If no case matches the expression value, the code within the default block (if present) is executed. The default case is optional.
- The break statement is used to terminate the switch block. Without it, the code execution would “fall through” to the next case block, leading to unintended behavior.
Here’s an example to illustrate the usage of a switch statement:
#include <stdio.h> int main() { int choice; printf("Enter a number between 1 and 3: "); scanf("%d", &choice); switch (choice) { case 1: printf("You entered 1.\n"); break; case 2: printf("You entered 2.\n"); break; case 3: printf("You entered 3.\n"); break; default: printf("Invalid choice.\n"); break; } return 0; }
In this example, the user is prompted to enter a number. The value is then compared using a switch statement, and the corresponding message is printed based on the entered value. If the user enters a number other than 1, 2, or 3, the default case is triggered, and an “Invalid choice” message is displayed.
Note that the expression inside the switch statement must be of an integer type (char, short, int, or long) or an enum type. Floating-point types, strings, and other non-integer types are not allowed in the expression.
Rules for switch statement in C language:
When using the switch statement in the C programming language, there are several rules and guidelines to keep in mind:
- The expression inside the switch statement must be of an integer type (char, short, int, or long) or an enum type. Floating-point types, strings, and other non-integer types are not allowed.
- Each case label must be a constant expression or a literal value. Variables or expressions that are not compile-time constants cannot be used as case labels.
- The case labels must be unique within the switch statement. Duplicate case labels are not allowed.
- The default case is optional and is executed if none of the case labels match the value of the expression. It can appear anywhere within the switch statement, but conventionally it is placed at the end.
- The break statement is used to terminate the execution of a case block. Without the break statement, the execution would “fall through” to the next case, leading to unintended behavior. The break statement is not required for the default case.
- It is common to include a break statement at the end of each case block, but if you want to execute multiple case blocks together, you can omit the break statement after each case. The execution will continue to the next case block until a break statement is encountered or the switch statement ends.
- The switch statement can be nested within other switch statements or control structures such as if statements or loops.
- The switch statement does not support range checking. It only performs equality checks. If you need to check for ranges, you can use a series of if statements instead.
- Variables declared inside a case block are local to that block and cannot be accessed outside of it. However, variables declared before the switch statement can be used within the switch statement and its case blocks.
- The order of case labels is significant. The execution will start from the first case that matches the value of the expression and continue until a break statement is encountered or the end of the switch statement is reached.
By following these rules, you can effectively use the switch statement to handle multiple alternatives based on the value of an expression in C.
Flowchart of switch statement in C:
Here is a basic flowchart representing the structure and flow of a switch statement in C:
+---------------+ | | | Start | | | +-------+-------+ | +------v------+ | | | Expression | | evaluated | | | +-------+-----+ | +-------v-----+ | | | Switch | | Statement | | | +-------+-----+ | +-------v-----+ | | | Case 1 | | | +-------+-----+ | +-------v-----+ | | | Code 1 | | | +-------+-----+ | | +-------v-----+ | | | Case 2 | | | +-------+-----+ | +-------v-----+ | | | Code 2 | | | +-------+-----+ | | +-------v-----+ | | | Case 3 | | | +-------+-----+ | +-------v-----+ | | | Code 3 | | | +-------+-----+ | | +-------v-----+ | | | Default | | | +-------+-----+ | +-------v-----+ | | | Code | | (if any) | | | +-------+-----+ | +-------v-----+ | | | End | | | +-------+-----+ | +--------v------+ | | | Exit | | | +---------------+
The flowchart starts with the “Start” symbol and then moves to the expression, which is evaluated. The flow then enters the switch statement, where the value of the expression is compared to the case labels.
If the expression matches one of the case labels, the corresponding code block is executed, followed by a break statement. After executing the code block, the flowchart moves to the next step outside the switch statement.
If the expression does not match any of the case labels, the flowchart proceeds to the “Default” case (if present) and executes the corresponding code block. Again, a break statement is not required for the default case.
Finally, the flowchart reaches the “End” symbol, indicating the end of the switch statement. From there, it proceeds to the “Exit” symbol, representing the end of the program or the continuation of the flow in the program.
Please note that the flowchart represents a general structure and flow of a switch statement. The specific details and logic within each code block may vary depending on the actual implementation.
Functioning of switch case statement:
The switch case statement in C is used to select one of many code blocks to execute based on the value of a given expression. It provides an efficient way to handle multiple alternatives without the need for multiple if-else statements. Here’s how the switch case statement functions:
- The expression inside the switch statement is evaluated.
- The value of the expression is compared to the case labels listed within the switch statement.
- If a case label matches the value of the expression, the corresponding code block following that case label is executed. Execution starts at that point and continues until the end of the code block or until a break statement is encountered.
- If the value of the expression does not match any of the case labels, execution either moves to the next case label (if present) or to the default case (if defined).
- The default case is optional and is used when none of the case labels match the expression value. If a default case is defined, the code block associated with the default case is executed.
- After executing the code block for a matching case or the default case, execution continues with the statement following the switch statement unless a break statement is encountered. The break statement is used to exit the switch statement and prevent execution from “falling through” to the next case.
Here’s an example to illustrate the functioning of the switch case statement:
#include <stdio.h> int main() { int day = 3; 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; default: printf("Weekend\n"); break; } return 0; }
In this example, the variable day
is set to 3. The switch statement compares the value of day
with each case label. Since day
is equal to 3, the code block following the case 3 label is executed, which prints “Wednesday” to the console. The execution then reaches the break statement, and the switch statement terminates. In this case, there is no need for the default case since there is a matching case for the value of day
.
The switch case statement provides a structured way to handle multiple conditions based on the value of an expression, making code more readable and efficient. It is often used in scenarios where there are many possible alternatives to consider.
Nested switch case statement:
In C, it is possible to have nested switch case statements, where a switch statement is nested within another switch statement. This allows for handling more complex and hierarchical decision-making scenarios. Here’s an example to illustrate the concept of nested switch case statements:
#include <stdio.h> int main() { int category = 2; int subcategory = 1; switch (category) { case 1: printf("Category 1\n"); switch (subcategory) { case 1: printf("Subcategory 1\n"); break; case 2: printf("Subcategory 2\n"); break; default: printf("Invalid Subcategory\n"); break; } break; case 2: printf("Category 2\n"); switch (subcategory) { case 1: printf("Subcategory 1\n"); break; case 2: printf("Subcategory 2\n"); break; default: printf("Invalid Subcategory\n"); break; } break; default: printf("Invalid Category\n"); break; } return 0; }
In this example, there are two levels of nested switch case statements. The outer switch statement checks the value of the category
variable, and based on its value, it enters the corresponding code block.
Within each category’s code block, there is an inner switch statement that checks the value of the subcategory
variable. Depending on the value of subcategory
, the corresponding code block is executed.
The output of this example, given the values of category = 2
and subcategory = 1
, would be:
Category 2 Subcategory 1
By using nested switch case statements, you can handle more complex decision-making scenarios where there are multiple levels of conditions and alternatives to consider. However, it is important to ensure proper indentation and readability to maintain the clarity of the code.