Switch statement in c++
Switch statement allows us to execute one statement from many statement an that statements ate called case. Actually in switch statement,inside the body
of switch a number of cases are used and a parameter are passed and from which case ths parameter is matched, executed
Syntax:
switch(expression)
{
case constant_1 :
// Code to be executed if expression == constant_1
break;
case constant_2 :
// Code to be executed if expression == constant_2
break;
default : // the default case is optional
// Code to be executed if none of the cases match.
}
- In the switch statement a value/number is passed in the place of parameter and that case will execute which is equal to that value/number.
- If no case matched with parameter then default case will execute.
Example:
#include< iostream.h >
void main()
{
int a=1;
switch(a)
{
case 1 :
cout<< "welcome to Tutorial Zone";
break;
case 2 :
cout<<"welcome";
break;
default :
cout<< "do not match:";
<
}
}
Output:
Rules
There are some rules to keep in mind while writing switch statements:
- The expression in the switch can be a variable or an expression - but it must be an integer or a character.
- You can have any number of cases however there should not be any duplicates. Switch statements can also be nested within each other.
- The optional default case is executed when none of the cases above match.
- The break statement is used to break the flow of control once a case block is executed.
NOTES:
break is not needed after the default case. This is because control would naturally exit the switch statement anyway.