C++ Tutorial · Chapter 8 of 13
C++ Switch
Menu-style selection.
switch works well for discrete choices such as 1, 2, 3.
Use break after each case unless fall-through is intentional.
Switch sample
Try it Yourself »
#include <iostream>
using namespace std;
int main() {
int choice;
cout << "1. Add\n2. Subtract\nChoose: ";
cin >> choice;
switch (choice) {
case 1: cout << "Addition selected" << endl; break;
case 2: cout << "Subtraction selected" << endl; break;
default: cout << "Invalid choice" << endl;
}
return 0;
}
Classroom Tips
- Add a default branch for invalid menus.