The switch statement in C++ allows for the execution of one block of code among multiple options based on the value of a variable. It is an alternative to using multiple if-else statements and is particularly useful when you have a variable that can take one of many distinct values.
The switch statement evaluates an expression and executes the block of code associated with the matching case label. If no case matches, the default block, if present, is executed.
switch(expression) {
case constant1:
// Code to execute if expression equals constant1
break;
case constant2:
// Code to execute if expression equals constant2
break;
// You can have any number of case statements
default:
// Code to execute if none of the cases match
}
Here is a simple example of a switch statement where the variable day
is checked against several case labels to print the name of the day.
#include <iostream>
using namespace std;
int main() {
int day = 4;
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 day";
}
return 0;
}
Console Output:
Thursday
The default case in a switch statement is executed when none of the case values match the expression. It is optional but recommended for handling unexpected values.
#include <iostream>
using namespace std;
int main() {
int month = 13;
switch(month) {
case 1:
cout << "January";
break;
case 2:
cout << "February";
break;
// Other cases omitted for brevity
case 12:
cout << "December";
break;
default:
cout << "Invalid month";
}
return 0;
}
Console Output:
Invalid month
In C++, if you omit the break
statement, the program will continue executing the following cases until it encounters a break
or the end of the switch block. This is known as fall-through.
#include <iostream>
using namespace std;
int main() {
int number = 2;
switch(number) {
case 1:
cout << "One";
case 2:
cout << "Two";
case 3:
cout << "Three";
break;
default:
cout << "Not in range";
}
return 0;
}
Console Output:
TwoThree
Switch statements can be nested inside one another. This is useful when you need to evaluate multiple conditions in a hierarchical manner.
#include <iostream>
using namespace std;
int main() {
int outer = 1, inner = 2;
switch(outer) {
case 1:
cout << "Outer is 1\n";
switch(inner) {
case 1:
cout << "Inner is 1";
break;
case 2:
cout << "Inner is 2";
break;
}
break;
default:
cout << "Outer is not 1";
}
return 0;
}
Console Output:
Outer is 1
Inner is 2
Switch statements can also be used with character data types. Here is an example where a character variable is evaluated in a switch statement.
#include <iostream>
using namespace std;
int main() {
char grade = 'B';
switch(grade) {
case 'A':
cout << "Excellent!";
break;
case 'B':
cout << "Good";
break;
case 'C':
cout << "Fair";
break;
default:
cout << "Invalid grade";
}
return 0;
}
Console Output:
Good
Enums provide a way to define named integer constants. Switch statements can be used to handle different enum values, improving code readability.
#include <iostream>
using namespace std;
enum Direction { UP, DOWN, LEFT, RIGHT };
int main() {
Direction dir = LEFT;
switch(dir) {
case UP:
cout << "Moving up";
break;
case DOWN:
cout << "Moving down";
break;
case LEFT:
cout << "Moving left";
break;
case RIGHT:
cout << "Moving right";
break;
default:
cout << "Invalid direction";
}
return 0;
}
Console Output:
Moving left
Omitting the break
statement can lead to fall-through behavior, where multiple case blocks are executed. This can be intentional for executing the same code for multiple cases.
#include <iostream>
using namespace std;
int main() {
int score = 3;
switch(score) {
case 1:
case 2:
case 3:
cout << "Low score";
break;
case 4:
case 5:
cout << "High score";
break;
default:
cout << "Invalid score";
}
return 0;
}
Console Output:
Low score
Sometimes, multiple cases require the same execution block. This can be efficiently handled by grouping cases together without a break
in between.
#include <iostream>
using namespace std;
int main() {
char vowel = 'e';
switch(vowel) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
cout << "It's a vowel";
break;
default:
cout << "It's a consonant";
}
return 0;
}
Console Output:
It's a vowel
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies