Case Control Structure(SWITCH) in C lang
Posted by
Ravi Kumar at Wednesday, August 31, 2011
Share this post:
|
Introduction:
In real life we are often faced with situations
where we are required to make a choice between a number of
alternatives rather than only one or two. Serious C
programming is same, the choice we are asked to make is
more complicated than merely selecting between two alter
natives. C provides a special control statement that allows
us to handle such cases effectively; rather than using a
series of IF statements.
Decisions Using Switch:
The control statement that allows us to make
a decision from the numbers of choices is called a SWITCH,
or more correctly a Switch-Case-Default, Since these 3
keywords go together to make up the control statement.They
most often appear as Follows:
switch(inter expression)
{
case constant 1:
do this;
case constant 2:
do this;
case constant 3:
do this;
default:
do this;
}
The integer expression following the keyword SWITCH is
any C expression that will yield an integer constant like
1,2 or 3, or an expression that evaluates to an integer.
The keyword case is followed by an integer or a character
constant.
Process of Execution:
When we run the program containing the switch,
first the integer expression following the keyword switch
is evaluated. The value it gives is then matched ,one by
one, against the constant values that follow the case
statements. When a match is found, the program executes
the statements following that case, and all subsequent case
and default statements. If no match is found with any of the
case statements, default is executed.
Example:
main()
{
int i=1;
switch(i)
{
case 1:
printf("I am in case1");
case 2:
printf("This is second one");
case 3:
printf("This is third case");
default :
printf("your are in default");
}
}
OUTPUT:
The output of this program would be:
I am in case1
This is second one
This is third case
your are in default
The output is definitely not what we expected. We
didn't expect 2nd,3rd and default cases print output.If you
want only case 2 should get executed,it is up to you to get
out of the switch then and there by using a Break statement.
Note that there is no need for a break statement after the
default,since the control comes out of the switch anyway.