Switch statement in Programming
Last Updated :
22 Mar, 2024
Switch statement in programming enables the execution of different code blocks based on the value of an expression, providing a structured approach to handle multiple cases efficiently. It enhances code readability and simplifies decision-making processes, making it a valuable tool for managing program flow and facilitating branching logic in software development.
What is Switch Statement?
Switch statement is a fundamental building block in many programming languages. It allows us to efficiently handle situations where the program needs to perform different actions based on different values of a variable.
For Eg: Imagine you're writing a program for a lift. The user selects a floor by pressing a button, and the lift needs to take the user to the selected floor. A switch statement is a great tool for such a scenario! By comparing the user's selection with different cases, the program can execute the appropriate code.
Syntax and Structure of Switch Statement:
A switch statement typically consists of the following elements.
- Switch expression: This is an expression that is evaluated to determine which case to execute. Commonly, it's an integer or a character variable.
- Case Statement: These statements define the different possible values the switch expression can take and the corresponding code to be executed if there's a match.
- Case block: This block contains the code to be executed based on the value of the switch expression.
- Break statement: This statement terminates the execution of the case block once a matching case is found. Without a break, the program might continue executing code from subsequent cases.
The syntax and structure of switch-case statements are similar across languages, with slight syntactic variations. Here is a general template.
Code Snippet
switch (switch_expression) {
case value1:
// Code to execute if switch_expression equals value1
break;
case value2:
// Code to execute if switch_expression equals value2
break;
// ... more cases
default:
// Code to execute if no matching case is found (optional)
}
Now let's dive into the details of each of the components of a switch-case statement.
Case Statement:
Each case statement defines a possible value the switch expression can take. The syntax usually involves the case keyword followed by the constant value.
case value:
// Code to execute when switch_expression equals value
The program checks each case statement sequentially until it finds a match with the switch expression's value. Once a match is found, the corresponding code block is executed.
Break Statement:
The break statement is an important element within the switch block. After a matching case is executed, the break statement terminates the switch block entirely, preventing the program from accidentally falling through and executing code from subsequent cases. This is also called fallthrough behaviour.
Here's an example to illustrate this.
// This is just a pseudo-code
switch (day) {
case 1:
print("Monday");
break;
case 2:
print("Tuesday");
// Without a break here, Wednesday will also be printed if day is 2!
case 3:
print("Wednesday");
break;
// ... more cases
}
In this example, if day is 2, both "Tuesday" and "Wednesday" will be printed without the break statements.
Default Statement:
The default statement in programming is a fallback option used in switch statements. It is executed when none of the case labels match the value of the expression being evaluated.
switch (expression) {
case value1:
// Code block to execute if expression matches value1
break;
case value2:
// Code block to execute if expression matches value2
break;
// More cases...
default:
// Code block to execute if expression does not match any case
}
Switch Statement in C:
Here are the example of Switch Statement in C language:
C
#include <stdio.h>
int main()
{
int day = 2;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thrusday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Not a valid number");
}
return 0;
}
Switch Statement in C++:
Here are the example of Switch Statement in C++ language:
C++
#include <iostream>
using namespace std;
int main()
{
int day = 2;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
default:
cout << "Not a valid number";
}
return 0;
}
Switch Statement in Java:
Here are the example of Switch Statement in java language:
Java
public class DayOfWeek {
public static void main(String[] args)
{
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Not a valid day number");
}
}
}
Switch Statement in Python:
Before Python 3.10, there was no feature for Switch statement in Programming. In Python 3.10, they have included match and case statement to implement Switch Case in Programming. Instead of default: case, we write case _: and there is no need to write break statement after each case.
Python3
day = 2
match(day):
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thrusday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
case _:
print("Not a valid number")
Switch Statement in C#:
Here are the example of Switch Statement in C# language:
C#
using System;
class DayOfWeek {
static void Main(string[] args)
{
int day = 2;
switch (day) {
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
// more cases
default:
Console.WriteLine("Not a valid day number");
break;
}
}
}
Switch Statement in JavaScript:
Here are the example of Switch Statement in javascript language:
JavaScript
let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
// more cases
default:
console.log("Not a valid day number");
}
Conclusion:
The switch statement in programming allows selecting different code paths based on a variable's value, providing a structured approach for handling multiple cases efficiently. While beneficial for readability and decision-making, it's crucial to use switch statements judiciously and explore alternative strategies for complex logic.
Similar Reads
Jump Statements in Programming
Jump statements in programming allow altering the normal flow of control within a program. These statements provide a way to transfer the execution to a different part of the code, facilitating conditional exits, loop control, function return, or unconditional jumps. Table of Content What is a Jump
6 min read
Goto Statement in Programming
Goto statement is a control flow statement present in certain programming languages like C and C++. It enables programmers to transfer program control to a labeled section of code within the same function or block. Despite its availability, its usage is often discouraged in modern programming practi
3 min read
If Else If Statement in Programming
If else if statement in programming allows you to check multiple conditions sequentially and execute different blocks of code based on those conditions. It's a way to handle various cases and make decisions within a program efficiently. Table of Content What is If Else If Statement?Syntax of If Else
4 min read
Control flow statements in Programming
Control flow refers to the order in which statements within a program execute. While programs typically follow a sequential flow from top to bottom, there are scenarios where we need more flexibility. This article provides a clear understanding about everything you need to know about Control Flow St
15+ min read
Break vs Continue Statement in Programming
Break and Continue statements are the keywords that are used always within a loop. The purpose of a break and continue statement is to stop a running loop or to continue a particular iteration. In this article we will see what are the break and continue statements, what is their use and what are the
4 min read
VBA Switch Statement
In Visual Basic for Applications (VBA), when a user needs to execute a series of statements depending on the value of an expression, they turn to the versatile tool known as the "Switch Case." This construct allows programmers to define multiple cases, each representing a different value, and then "
5 min read
Nested Switch Statements in Objective-C
Like most of the popular programming languages, Objective-C also allows using decision control statements, namely Switch-Case statements. This statement has an expression part, and a cases-value part, where each case contains a unique value. After evaluating the logical expression, the result of tha
7 min read
Variables in Scratch Programming
Scratch is a high-level visual programming language tool that interacts with users through diagrams and blocks that have the basics of a program inbuilt in it. Scratch is used to make interactive programs especially for kids using the block kind of interfaces so that they can easily learn languages
7 min read
Variable in Programming
In programming, we often need a named storage location to store the data or values. Using variables, we can store the data in our program and access it afterward. In this article, we will learn about variables in programming, their types, declarations, initialization, naming conventions, etc. Table
11 min read
Swift - Fallthrough Statement
Just like other languages in Swift also switch statement is very useful and powerful. It takes a value and then compare it with several possible matching pattern or we can say cases and stops its execution when it successfully found its first matching case statement and then execute the code present
4 min read