next up previous
Next: Arrays Up: Overview of C++ Previous: Activity

switch Statement

The switch statements work is sometimes called the multiple-choice statement. The switch statement lets the program to choose from several alternatives. The general form of the switch statement is

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:$\backslash$n$\backslash$n";
cout << "1. for $\backslash$n";
cout << "2. if $\backslash$n";
cout << "3. switch $\backslash$n";
cout << "Enter choice :(1-3):";
cin>> ch;
switch(ch){
case 1:
cout << "for is one type of C++ loops$\backslash$n";
break; case 2:
cout << "if is C++ conditional statement $\backslash$n";
break;
case 3:
cout << "Switch is C++ multiple-choice statement $\backslash$n";
break;
default:
cout <<"You must enter a number between 1 and 3 $\backslash$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 $\backslash$n";
case 1: cout << "less than 2 $\backslash$n";
case 3: cout << "less than 3 $\backslash$n";
case 4: cout << "less than 4 $\backslash$n";
}
cout << '$\backslash$n'; }
return 0;
}


next up previous
Next: Arrays Up: Overview of C++ Previous: Activity
Yousef Haik
2/23/1998