Switch Statement in C/C++

12 Jun, 2022
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). 
Switch case statements follow a selection-control mechanism and allow a value to change control of execution.
They are a substitute for long if statements that compare a variable to several integral values.
The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
In C++, the switch statement is used for executing one condition from multiple conditions. It is similar to an if-else-if ladder.
Switch statement consists of conditional based cases and a default case.
In a switch statement, the “case value” can be of “char” and “int” type.Following are some of the rules while using the switch statement:1. There can be one or N numbers of cases.2. The values in the case must be unique.3. Each statement of the case can have a break statement. It is optional.
Syntax: 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
switch(expression)
{    
case value1:    statement_1; break;
    
case value2:    statement_2; break;

.....
......
......
case value_n:    statement_n; break;


default:     default statement;
 
}    
C++
// Q: WA C++ program to returns day based on the numeric value. #include<iostream>using namespace std; class Day{    private:        int day;             public:        void set_data()        {            cout<<"Enter no of day you want to display: ";            cin>>day;        }                 void display_day()        {            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<<"INVALID INPUT";                    break;            }        }}; main(){    Day d1;         d1.set_data();    d1.display_day();         return 0;}
Some important keywords:
1) Break: This keyword is used to stop the execution inside a switch block. It helps to terminate the switch block and break out of it.
2) Default: This keyword is used to specify the set of statements to execute if there is no case match.
Note: Sometimes when default is not placed at the end of switch case program, we should use break statement with the default case.
Important Points About Switch Case Statements:  
1) The expression provided in the switch should result in a constant value otherwise it would not be valid. Some valid expressions for switch case will be,
// Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)

// Variable expression are allowed provided
// they are assigned with fixed values
switch(a*b+c*d)
switch(a+b+c)
2) Duplicate case values are not allowed.
3) The default statement is optional. Even if the switch case statement do not have a default statement, it would run without any problem.
4) The break statement is used inside the switch to terminate a statement sequence. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
5) The break statement is optional. If omitted, execution will continue on into the next case. The flow of control will fall through to subsequent cases until a break is reached.
6) Nesting of switch statements is allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes the program more complex and less readable. 
7) Switch statements are limited to integer values and characters only in the check condition.Flowchart: 
Example 1:
C
C++
// C program to demonstrate syntax of switch#include <stdio.h> // Driver Codeint main(){    int x = 2;    switch (x) {    case 1:        printf("Choice is 1");        break;    case 2:        printf("Choice is 2");        break;    case 3:        printf("Choice is 3");        break;    default:        printf("Choice other than 1, 2 and 3");        break;    }    return 0;}
// C++ program  to demonstrate syntax of switch#include <iostream>using namespace std; // Driver Codeint main(){    int x = 2;    switch (x) {    case 1:        cout << "Choice is 1";        break;    case 2:        cout << "Choice is 2";        break;    case 3:        cout << "Choice is 3";        break;    default:        cout << "Choice other than 1, 2 and 3";        break;    }    return 0;}
Choice is 2
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 2:
C
C++
// C program to demonstrate syntax of switch#include <stdio.h> // Driver Codeint main(){    char x = 'A';    switch (x) {    case 'A':        printf("Choice is A");        break;    case 'B':        printf("Choice is B");        break;    case 'C':        printf("Choice is C");        break;    default:        printf("Choice other than A, B and C");        break;    }    return 0;} //Code submitted by Susobhan AKhuli
// C++ program  to demonstrate syntax of switch#include <iostream>using namespace std; // Driver Codeint main(){    char x = 'A';    switch (x) {    case 'A':        cout << "Choice is A";        break;    case 'B':        cout << "Choice is B";        break;    case 'C':        cout << "Choice is C";        break;    default:        cout << "Choice other than A, B and C";        break;    }    return 0;} //Code submitted by Susobhan AKhuli
Choice is A
Output:
Choice is A
Time Complexity: O(1)
Auxiliary Space: O(1)
C
C++
//switch statement to demonstrate multiple cases with unique labels#include <stdio.h> int main() {    char n='C';  switch(n)  {    case 'A':    case 'B':       printf("A and B\n");      break;           case 'C':    case 'D':      printf("C and D\n");      break;           default:printf("Alphabet is greater than D\n");      break;  }  return 0;         } //code submitted by pinto kumar
//switch statement to demonstrate multiple cases with unique labels#include <iostream>using namespace std; int main(){  char n='C';  switch(n)  {    case 'A':    case 'B':       cout<<"A and B"<<endl;      break;           case 'C':    case 'D':      cout<<"C and D"<<endl;      break;           default:cout<<"Alphabet is greater than D"<<endl;      break;  }  return 0;} //code submitted by pinto kumar
C and D
 Time Complexity: O(1)
Auxiliary Space: O(1)
C++ Programming Language Tutorial | Writing first C++ program : Hello World example | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersC++ Programming Language Tutorial | Writing first C++ program : Hello World example | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:04•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=37GG-T6B7bc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Must Read:
Interesting Facts About Switch Case in C
What should be Data type of Case Labels of Switch Statement in C?
Print Individual Digits as Words Without Using if or Switch
This article is contributed by Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
arvindnikesh
subhammahato348
atharvawadkar1
tusharkhanna5112
anshikajain26
susobhanakhuli
pintoyadavof
aditiyadav20102001
C Basics
CPP-Basics
C Language
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.