
We trust you have understood the significance of the switch construct from the preceding summary. You would surely have noticed that the only keyword in the switch that does not have a peer in the if-else-if-else construct is the 'break' keyword. We never used such a keyword in the if cascades because the language standard took care of the comparison-execute-exit mechanism all by itself.
The language does not guarantee by itself the third part, that's, the exit mechanism. This is the stand-out difference between the two conditional constructs. The programmer is expected to take control of the exit mechanism by using the 'break' keyword. We can illustrate this more succinctly by looking at an example. Consider the following scenario:
A model is applying for work at a modeling agency and wants to become the next supermodel. The application form has a field called 'Sex' where the model has to enter the relevant entry from the choices {'M', 'F', 'B'}... Male, Female, Both.
Pseudo-code of a program that scans applications for registration would look like:
switch(sex)
{
case 'M' : trace("Male");
case 'F' : trace("Female");
default: trace("Transsexual");
}
What would the output be if the value entered by the model was 'M' (male)?Let's cut the crap and go straight to the heart of the matter. The output of the above program, when run, turns out to be:
Male Female TranssexualSurprising, isn't it? Even though the model correctly entered his sex to be 'M', the computer program we wrote forced him to be all 3 choices. That does not normally happen in the real world, though. This issue has everything to do with the exit mechanism of switch, which has to be taken care of by the programmer. Watch carefully... the correct way to write code for the scanner program would be:
switch(sex)
{
case 'M' : trace("Male");
break;
case 'F' : trace("Female");
break;
default: trace("Transsexual");
break;
}
Now, the program will correctly print 'M' for the same model. Got the hang of it? This is the only catch with the switch construct. Now, we would like you to predict the output of the following code chunk if sex="M" (there might be cookies involved!):
switch(sex)
{
case 'M' : trace("Male");
case 'F' : trace("Female");
break;
default: trace("Transsexual");
}
If you correctly guessed that the output would be:
Male FemaleYOU get a cookie! Got it? Great! You are now an oracle on switch behavior!
Have a question but don't want to ask it publicly? If you are a prime member just ask right here and we will get back to you within 48 hours. Not prime yet? no worries you can ask publicly below.