C++ switch statement
switch is multi way conditional control statement. which allow to execute multiple operations for the different values.it help us to make choice on the number of alternatives.
Here the syntax of switch statement is
(expression)
{
constant1:
statement
………
constant2:
statement
………
………
constantn:
statement
………
statement
………
}
|
in the above example switch, case and default are keywords. The expression following in the switch keyword can be integer or character expression. Then the constant expression in the case label should be of character or integer type. Every constant should be different from another (each case value should be different or unique) and we can not use float or string constant in case. multiple constant in a single case not allowed only one constant allow. In each case followed by any number of statements. The statements under any case can be any valid C statements like for, do-while, while, if-else etc or can give another switch statement inside switch, declare another switch statement inside switch statement is call nesting of switches
Let us take example how switch case works
<iostream>
main()
{
choice;
std::cout<<"Enter any choice 1,2,3";
std::cin>>choice;
(choice)
{
1:
std::cout<<"Choice is one";
;
2:
std::cout<<"choice is two";
;
3:
std::cout<<"choice is three";
;
:
std::cout<<"wrong choice";
}
0;
}
|
let us discuss how switch statement works
firstly the switch control statement expression evaluated. if the expression value is matched with the case constant expression. Then the control transfer to the case label. but if the any case label not match with switch expression then control is transfer to the default label. The default label is optional. but in this example break keyword are used. break keyword is used to bring the program control out of the loop or block.
so here is the example after execute any case label break keyword jump to the out of the switch statement. The break keyword can be use inside any loop, block etc
Valid Switch |
Invalid switch |
valid case |
invalid case |
switch(a) |
switch(x) |
case 10 |
case 12.9 |
switch(a+b) |
switch(x-2.8) |
case ‘A’ |
case a |