Professional Documents
Culture Documents
The control statement which that allows us to make a decision from a number of choices is
called switch (switch-case-default).An integer expression or a statement which yields an
integer value should follow switch. Keyword case should be followed by an integer or a
character constant . Each constant should be different.The ‘do this’ lines are any valid C
statement.
It is similar to the scene in CID when the ACP tries to match face in a photograph with a
person in a group of arrested people. He starts with whoever is first in the line (this means
that order of persons is not important- same is with C language. “Order of cases is not
important”) . He matches the face if not matched , he moves on to the next . This continues
till he has finished all people. Agar koi face match nahi hota hai to ACP us isaan ko pakadta
hai jis par use pehle se hi shak tha (default statement).
Agar hum har case ke baad break; nahi lagaye to computer matching case ke baadd aane
waale sabhi cases ko evaluate kar dega. Isliye break lagana bahut zaroori hai.
LUC 4.1 :
I just tried out a program on switch statement. The problem is that it accepts only integer
values and also that we cannot put ranges in case .
LUC 4.2 We can use char values in case and switch .
We can use char values in case and switch . Actually , all the character constants are
replaced by their ASCII values.
Even if there are multiple statements to be executed in a single case , there is no need of
enclosing them in braces (unlike if-else).
Every statement in a switch must belong to a case . If it doesn’t , compiler won’t report an
error but that very statement will not be executed.
It is also possible that a switch does not have any default statement. In that case the
program simply falls through the entire switch and follows up the next instruction(if any)
that follows the closing brace of switch.
** We can check the value of any expression in switch . Following statements are valid :
switch(i*j+3)
switch(23 +45%4*k)
switch(a<4 && b>7)
Expressions can also be used in cases provide they are constant expressions. Thus case 3+4
is correct but case a+b is incorrect.
5.7 ? : operator
The ? : operator is used like the if-else statement. It is generally used like :
name = (conditional expression) ? exp1 : exp2
The conditional expression is evaluated first. If the result is non-zero , exp1 is evaluated and
returned as the value of the conditional expression. Otherwise, exp2 is evaluated and its
value returned.
5.8