switch(condition){
case 1:
statement sequence;
break;
case 2:
statement sequence;
break;
..
..
default:
statement sequence;
}
The switch expression must evaluate to either a character or an integer value. Floating point expressions are not allowed. The default statement sequence is performed if no matches are found. The default is optional, if it is not present no action takes place if all matches fail. When a match is found, the statements associated with that case are executed until the break is encountered. In the case of default or the last case, until the end of the switch is reached.
Example
// demonstrate the switch using simple help program
#include <iostream>
main()
{
int ch;
cout << "help on:nn";
cout << "1. for n";
cout << "2. if n";
cout << "3. switch n";
cout << "Enter choice :(1-3):";
cin>> ch;
switch(ch){
case 1:
cout << "for is one type of C++ loopsn";
break;
case 2:
cout << "if is C++ conditional statement n";
break;
case 3:
cout << "Switch is C++ multiple-choice statement n";
break;
default:
cout <<"You must enter a number between 1 and 3 n";
}
return 0;
}
Example
/* this example illustrates that execution will continue to the next case if no break statement
is present */
#include <iostream.h>
main()
{
int i;
for(i=0;i<5;i++) {
switch(i) {
case 0: cout << "less than 1 n";
case 1: cout << "less than 2 n";
case 3: cout << "less than 3 n";
case 4: cout << "less than 4 n";
}
cout << 'n';
}
return 0;
}