The switch statement in C++ Programming:-
The switch statement provides no control that an if statement does not; it simply allows for neater code. It is used in the particular case where there is a set of possible values for some variable (called the control variable) and different actions must be taken for each one. The format is:
switch (<control variable>) {
case <value 1>: // actions if variable is value 1
break;
case <value 2>: // actions if variable is value 2
break;
default: // actions if variable had none of the values listed
}
Since it must be possible to list all the possible values of the control variable, if follows that the variable must be a char or an int. It is not possible to list all possible strings or all possible floating-point numbers. The effect of the statement is that the case containing the value is found, and the statements found there are executed. The end of the case is marked with break, and execution stops.
A switch statement would be suitable for printing the name of the month from a numeric representation of a date. There would be twelve possibilities, one for each month. Assuming that the month were stored in an integer variable month the code would be:
switch (month) {
case 1: cout << "January";
break;
case 2: cout << "February";
break;
case 3: cout << "March";
break;
case 4: cout << "April";
break;
// and so on for the other months
}
There would be no need for a default section in this case because all the possible values would presumably be known and listed. If it were possible that an invalid value could be held in month there are two possibilities. One is to add a default
section:
default: cout << "Error: Invalid Month!";
A potentially neater alternative is to keep the switch statement as it stands and to use it only if the value is found to be valid:
if (month >= 1 && month <= 12) {
switch (month) {
// switch cases
}
}
Only variables whose possible values can be listed can be used in switch statements; this effectively means only integers and characters. The default case means that it is not necessary to list all the possible values, of course.


LinkBack URL
About LinkBacks
Reply With Quote

LinkBacks Enabled by vBSEO
Bookmarks