Programming with C/C++ Language
Introduction to the C++ Language
switch case in C++
1. Switch case
Switch case statements are a substitute for long if statements
that compare a variable to several integral values.
integral values are simply values that can be expressed
as an integer, such as the value of a char.
The value of the variable given into switch is compared to the value
following each of the cases, and when one value matches the value of the variable,
the computer continues executing the program from that point.
Here is the basic format for using switch case :
switch ( ) {
case this-value:
Code to execute if == this-value
break;
case that-value:
Code to execute if == that-value
break;
...
default:
Code to execute if does not equal the
value following any of the cases
break;
}
Note the colon after the values of case.
The condition of a switch statement is a value.
The break is used to break out of the case statements.It is a keyword that
breaks out of the code block. It prevents the program from falling through and
executing the code in all the other case statements.
The case values may only be constant integral expressions.
The following code is not allowed:
int x = 12;
switch ( a ) {
case x:
// Code ..
break;
default:
// Code ..
break;
}
The default case is optional, but it is wise to include it as it
handles any unexpected cases.
Switch statements serves as a simple way to write long if statements
when the requirements are met. Often it can be used to process input
from a user.
2. Example
Here is an Example:
#include
using namespace std;
void write()
{
cout << "Write a poem";
}
void compose()
{
cout << "Compose this poem ";
}
void sing()
{
cout << "Sing the written composed poem ";
}
int main()
{
int input;
cout<<"1. Write a poem \n";
cout<<"2. Compose the poem \n";
cout<<"3. Sing the poem \n";
cout<<"4. Quit\n";
cout<<"Selection: ";
cin>> input;
switch ( input ) {
case 1:
write();
break;
case 2:
compose ();
break;
case 3:
sing();
break;
case 4:
cout<<"The song is done .. !\n";
break;
default:
cout<<"Error, incorrect input, quitting\n";
break;
}
cin.get();
}
This program will compile, but cannot be run until the is input
is processed.
Default simply skips out of the switch case construction and allows
the program to terminate naturally.
|