It has the following syntax:
switch(variable)
{
case 1:
//execute your code
break;
case n:
//execute your code
break;
default:
//execute your code
break;
In this syntax,
- Switch: It is the keyword that we have for the given statement.
- Expression: It is the value that has to be evaluated for every case present inside the switch block.
- Default: It is also a case that gets executed when no other case gets executed.
- Break: It is a keyword that gets executed when the matching case gets executed. Once the statements for the matching case finish, the break keyword comes into action, and comes out of it.
Flowchart of the Switch Statement in C
As demonstrated in the flowchart, follow these steps to incorporate the switch statement in the C programming language:
Initially, the compiler assesses the switch statement.
Afterwards, it compares the evaluated case value with the current case values.
In this stage, the program verifies the case value. When there is a match, the compiler moves on to run the instructions specified within that case. If no case values match, the default case is triggered and executed.
Afterward, if the 'break' keyword is included in the case block, the program control will exit the switch statement following the execution of that case block. In the absence of the 'break' keyword, all subsequent cases that follow the matching case will be executed.
Finally, after all the conditions have been checked in the switch block, the corresponding statements in the program file are executed.
C Switch Statement Example
Let's consider a scenario to demonstrate the switch statement in the C programming language.
Example
#include <stdio.h>
void main ()
{
int number = 0;
printf ("Enter a number: \n");
scanf ("%d", &number);
switch (number)
{
case 1:
printf ("Number is equals to 1");
break;
case 2:
printf ("Number is equal to 2");
break;
case 3:
printf ("Number is equal to 3");
break;
default:
printf ("Number is not equal to 1, 2, or 3");
}
}
Output:
Enter a number: 4
Number is not equal to 1, 2, or 3
Explanation:
In this instance, we've acquired an integer input from the user and employed a switch statement to evaluate the value against predefined cases (1, 2, and 3). When the input aligns with any case, it exhibits the relevant message; if not, the default case runs, signaling that the number isn't 1, 2, or 3.
Rules for Switch Statement in the C language
There are several rules for the Switch Statement in the C language. Some of them are as follows:
- In the C programming language, the switch expression must be of an integer or character type.
- The case value must be an integer or character constant.
- The case value should be used only inside the switch statement.
- The break statement in a switch case is not a must. It is optional. If there is no break statement found in the case, all the cases will be executed after the matched case. It is known as a fall through the state of the C switch statement.
Calculator Program using switch Statement in C
Let's consider an instance of a basic calculator implemented using a switch statement in the C programming language.
Example
#include <stdio.h>
int main() {
int num1, num2;
char op;
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &op); // space before %c to avoid newline issues
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
switch(op) {
case '+':
printf("%d + %d = %d\n", num1, num2, num1 + num2);
break;
case '-':
printf("%d - %d = %d\n", num1, num2, num1 - num2);
break;
case '*':
printf("%d * %d = %d\n", num1, num2, num1 * num2);
break;
case '/':
if (num2 != 0)
printf("%d / %d = %d\n", num1, num2, num1 / num2);
else
printf("Error! Division by zero is not allowed.\n");
break;
default:
printf("Invalid operator!\n");
}
return 0;
}
Output:
Enter an operator (+, -, *, /): +
Enter first number: 15
Enter second number: 20
15 + 20 = 35
Explanation:
In this instance, we develop a basic calculator that employs a switch statement to execute addition, subtraction, multiplication, or division depending on the operator provided by the user. Following that, we collect two numbers and an operator as input to carry out the relevant calculation.
Switch Statement with Logical Expression in C
Let's consider a scenario to demonstrate the switch statement with a logical condition in the C programming language.
Example
#include <stdio.h>
int main()
{
int x = 10, y = 5;
switch(x>y && x+y>0)
{
case 1:
printf("hi");
break;
case 0:
printf("bye");
break;
default:
printf(" Hello bye");
}
}
Output:
Explanation:
In this instance, we examine a switch statement that assesses the logical condition x > y && x + y > 0, yielding either 1 (true) or 0 (false). With x being larger than y and their total being positive, the condition resolves to 1. As a result, the application showcases the output "hi".
Nested Switch Case Statement
In C programming, it is possible to include multiple switch statements within another switch statement. This arrangement is known as a nested switch case statement, allowing for complex decision-making processes that depend on various conditions.
Syntax:
It has the following syntax:
switch (expression1) {
case value1:
switch (expression2) {
case valueA:
// Code for inner switch
break;
case valueB:
// Code for inner switch
break;
}
break;
case value2:
// Code for outer switch
break;
default:
// Default case for outer switch
}
C Nested Switch Case Example
Let's consider an instance to demonstrate nested switch statements in C programming.
Example
#include <stdio.h>
int main () {
int i = 10;
int j = 20;
switch(i) {
case 10:
printf("The value of i evaluated in the outer switch: %d\n", i);
case 20:
switch(j) {
case 20:
printf("The value of j evaluated in nested switch: %d\n", j);
}
}
printf("Exact value of i is : %d\n", i );
printf("Exact value of j is : %d\n", j );
return 0;
}
Output:
The value of i evaluated in the outer switch: 10
The value of j evaluated in nested switch: 20
Exact value of i is : 10
Exact value of j is : 20
Explanation:
In this instance, we showcase the nested switch case construct in C programming. The primary switch statement assesses the value of i. When i equals 10, it proceeds to execute its corresponding case block without a break, triggering the inner switch statement. Subsequently, the inner switch evaluates the value of j. Given that j is 20, it displays the value of j alongside the precise values of i and j.
C Switch Statement Fall-Through
In C programming, a switch statement fall-through happens when a break statement is omitted within a switch case. Without the break statement, program flow will continue to execute all subsequent case statements until it encounters a break or reaches the end of the switch statement block.
C Switch Statement Fall-Through Example
Let's consider a basic example to showcase the fall-through behavior of the switch statement in the C programming language.
Example
#include<stdio.h>
int main(){
int number=0;
printf("Enter a number: ");
scanf("%d", &number);
switch(number){
case 10:
printf("Number is equal to 10\n");
case 50:
printf("Number is equal to 50\n");
case 100:
printf("Number is equal to 100\n");
default:
printf("Number is not equal to 10, 50, or 100");
}
return 0;
}
Output:
Enter a number: 10
Number is equal to 10
Number is equal to 50
Number is equal to 100
Number is not equal to 10, 50, or 100
Explanation:
In this instance, the software requests user input for a numerical value. Following the input, the program flow proceeds to evaluate the corresponding case. In the absence of break statements, each subsequent case and the default block are executed as well, resulting in multiple outputs following the initial match.
Switch Statement using Break Keyword
In C programming, the "break" keyword is frequently employed within the code block of each case to end the switch statement prematurely. If a "break" statement is found within a case block, the program will exit the switch statement immediately, halting the execution of any following case blocks. This use of the "break" statement is crucial for preventing the unintended "fall-through" behavior in switch statements.
C Switch Statement Example using Break Keyword
Let's consider an example to showcase the usage of the break keyword within a switch statement.
Example
#include <stdio.h>
int main() {
int num = 3;
switch (num) {
case 1:
printf("Value is 1\n");
break; // Exit the switch statement after executing this case block
case 2:
printf("Value is 2\n");
break; // Exit the switch statement after executing this case block
case 3:
printf("Value is 3\n");
break; // Exit the switch statement after executing this case block
default:
printf("Value is not 1, 2, or 3\n");
break; // Exit the switch statement after executing the default case block
}
return 0;
}
Output:
Value is 3
Explanation:
In this instance, we are demonstrating a switch statement that assesses the value of the variable num (set to 3) and compares it with case 3. Subsequently, the block of code linked with case 3 is triggered, resulting in the output "Value is 3" being shown on the console. By including a "break" statement within case 3, it guarantees that the switch statement terminates its execution right after handling this particular case, preventing the execution of any subsequent cases.
Switch Statement using Default Keyword
In C programming, the default keyword within a switch statement proves valuable when there is no match with any case label for the given expression. It is frequently employed to address scenarios where none of the specified conditions correspond to the input received. This serves as a contingency plan and remains discretionary within a switch block.
C Switch Statement Example using Default Keyword
Let's consider a program to explore the functionality of the default keyword in the C programming language.
Example
#include <stdio.h>
int main() {
int num = 5;
switch (num) {
case 1:
printf("Value is 1\n");
break;
case 2:
printf("Value is 2\n");
break;
case 3:
printf("Value is 3\n");
break;
default:
printf("Value is not 1, 2, or 3\n");
break; // Exit the switch statement after executing the default case block
}
return 0;
}
Output:
Value is not 1, 2, or 3
Explanation:
In this instance, the switch statement evaluates the value stored in the variable num (in this case, 5). As there are no cases that correspond to the value of num, the program executes the code block linked to the "default" case. Subsequently, the "break" statement situated within the "default" case guarantees that the switch statement concludes execution after handling the "default" case block.
Advantages of the Switch Statement
There are several advantages of the switch statement in C. Some main advantages of the switch statement are as follows:
- The switch statement provides a concise and straightforward way to express multiway branching in the code. It deals with multiple cases that can make the code more organized and easier to read than multiple nested if-else statements.
- The switch statement is generally more efficient than a series of if-else statements when dealing with multiple conditions.
- It is useful in those cases where the program need to make decisions based on specific values of one variable. It is an easy and direct method to apply case-based logic.
- It allows the utilization of a default case, which is an option of values that do not correspond to any of the cases. This default case occurs when dealing with typical inputs or situations that are not stated.
Disadvantages of the Switch Statement:
There are several disadvantages of the Switch Statement in the C programming language. Some of them are as follows:
- The expression used in the switch statement must result in an integral value (char, int, enum) or a compatible data type. It cannot handle more complex or non-constant expressions, which reduces its flexibility in some specific cases.
- It only accepts integral types (integers) and values from enums; it does not accept floating-point numbers. It does not handle non-integral data types like floating-point integers, which might be problematic in some circumstances.
- Switch statements have "fall-through" behavior by default, which means that if a case does not include a "break" statement, the execution will "fall through" to the following case block. If it is not managed properly, it can result in unwanted behavior.
- Using a switch statement might result in duplicate code in some cases, especially when multiple cases require the same actions. If it is not properly managed, it can result in code duplication.
Conclusion
In summary, the switch statement serves as a crucial control mechanism primarily employed to run a single code block from various choices depending on an expression's value. Employing a switch statement enhances program readability and efficiency in contrast to employing numerous if-else statements. By utilizing case labels and the optional default keyword, it offers a straightforward approach to managing decision-making processes.