In C++, the switch statement allows programs to execute one of multiple possible code blocks based on a given value. It simplifies decision-making when dealing with fixed options, such as menu selections, categories, or predefined choices.
How the switch Statement Works
The expression inside switch() is evaluated once, and then its value is compared against different case labels.
- If a case matches, its block of code runs.
- If no match is found, the
defaultcase executes (if provided). - The
breakkeyword prevents further execution beyond the matched case.
Syntax
switch(expression) {
case value1:
// Code block
break;
case value2:
// Code block
break;
default:
// Code block if no cases match
}
Example: Identifying Motorcycle Categories
#include <iostream>
using namespace std;
int main() {
int bikeType = 2;
switch (bikeType) {
case 1:
cout << "Sport bike";
break;
case 2:
cout << "Cruiser";
break;
case 3:
cout << "Touring bike";
break;
case 4:
cout << "Off-road motorcycle";
break;
default:
cout << "Unknown category";
}
return 0;
}
If bikeType is 2, the output will be “Cruiser”.
The break Keyword
The break statement ensures that execution stops once a case is matched.
Without break, all subsequent cases would execute, causing unwanted behavior.
Example (Without break)
switch (bikeType) {
case 1:
cout << "Sport bike";
case 2:
cout << "Cruiser";
case 3:
cout << "Touring bike";
}
Even if bikeType is 1, all cases would execute, displaying “Sport bikeCruiserTouring bike”.
The default Keyword
The default case ensures that the program handles unexpected values by providing an alternative output.
Example
int carType = 5;
switch (carType) {
case 1:
cout << "Sedan";
break;
case 2:
cout << "SUV";
break;
default:
cout << "Unknown vehicle type";
}
Since carType is 5, and there is no matching case, the output will be “Unknown vehicle type”.


