The control statement which allows us to make a decision from the
number of choices is called a switch,
or more correctly a switch-case-default.
Since these three keywords go together to make up the control statement.
This is another form of the multi-way decision. It is well
structured, but can only be used in certain cases where:
Ø Only one variable is tested,
all branches must depend on the value of that variable. The variable must be an
integral type i.e. int, long, short or char.
Ø Each possible value of the
variable can control a single branch. A final, catch all, default branch may
optionally be used to trap all unspecified cases.
Ø Each statement is given as a
case label.
Syntax:-
If you have a large decision tree and all the decisions depend on
the value of the same variable you will probably want to consider a switch statement instead of a series.
The case label need not
appear in any particular order but each of the case labels must be unique. The
use of break statement in every case is used to quit the switch statement after
a particular case is matched, so only one case will get executed at one time.
If break is not used, then all statements followed by the match case will get
executed. Thus the break statement is must for the proper execution of the
switch statement.
1. Even if there are multiple
statements to be executed in each case
there is no need to enclose these within a pair of braces (unlike if and else).
2. They are allowed to use int and char values in case and switch statement.
i.
int i=22;
switch (i)
{
case 22:
}
ii.
char c = ’x’;
switch (c)
{
case ’x’:
}
3.
We can mix integer and
character constants in different cases
of switch.
i.
char c = ’x’;
switch (c)
{
case ’x’:
printf
("Hello");
break;
case 22:
printf
("Hi");
}
4.
It is case sensitive
language. Here, ’x’ and ’X’ are different.
i.
char c = ’X’;
switch (c)
{
case ’x’:
case ’X’:
}
5. If we have no default case, then the program simply
falls through the entire switch and continues with the next instruction (if
any) that follows the control structure.
6. Is switch a replacement for if?
Yes as well as no. Yes, because it
offers a better way of writing programs as compared to if, and No because in
certain situations we are left with no choice but to use if.
a. The disadvantage of switch is that one cannot have a case
in switch which looks like…..
case
i<=20;
All that we can have after the case is an int constant or a char constant. Even a float
is not allowed.
b. The advantage of switch over if is that it leads to a more structured program and the level of
indentation is manageable, more so if there are multiple statements within each
case of a switch.
7. The break statement when used in a switch
takes the control outside the switch.
However, use of continue will not
take the control to the beginning of switch
as one is likely to believe.
0 comments:
Post a Comment