switch (expression) { //Expr usually a variable or function call. case constant: //case values must be constants, not variables. //integral (int and char only). Not float, not string. stmts //The first case value that matches the expr, //its stmts executed. break; // terminates the switch. //Else will fall thru to next case's stmts case constant: stmts break; case constant: case constant: // either of two values stmts break; // can have as many cases as needed default: // optional. Catch-all, will execute if none //of the cases matched stmts }
int choice; cout << "Enter choice 1 - 5: "; cin >> choice; switch (choice) { case 1: //whatever the choice 1 stuff is break; case 2: //choice 2 stuff break; case 3: //do 3's code break; case 4: //bunch of stmts for 4 break; case 5: //5's statements here break; default: cout << "Invalid choice. 1 thru 5 only"; }
Simple calculator program. User enters num op num, eg. 10 * 4 program determines type of operation, performs calculation, outputs result.
(See program) simpcalc.cpp Try it
---------------------------------------------------------
"multiple choices:"
case '*': case 'x': result = num1 * num2; break;Can not do:
Any switch statement can be written as if, else if...
//calculator program revisited if (op == '+') result = num1 + num2; else if (op == '-') result = num1 - num2; else if (op=='*' || op=='x') result = num1 * num2; else if (op == '/') if (num2 == 0) cout << "Illegal divide by zero"; else result = num1 / num2; else cout << "Illegal operator";
But not every if, else if... could feasibly be turned into a switch:
if (val>0 && val<1000) //do action1 else if (val>=1000 && val<2000) //do action2A switch for this would require 2000 cases. switch is not good for range of values.
Next (for)