-
Switch Case Question
I was doing the quiz on this website dealing with Switch Case and I have a question. Question 4 states
Code:
4. What is the result of the following code?
x=0;
switch(x)
{
case 1: cout<<"One";
case 0: cout<<"Zero";
case 2: cout<<"Hello World";
}
A. One
B. Zero
C. Hello World
D. ZeroHello World
The answer is D. Why is it D? I understand there is no break statement but for it to execute case 2 the value of x would need to be 2 but its 0. Why is Hello World getting outtputted when the case value is not met?
-
switch statements "fall through"; that is, the code keeps executing until a break statement [edit=2] or the end of the switch [/edit] is reached. The case label only indicates where the code starts executing when the case value is met.
So because there isn't a break for case 0, the execution "falls through" and the code for case 2 is executed as well.
[edit]
To see the fall-though effect, try this program:
Code:
#include <iostream>
using std::cout;
using std::endl;
int main(void) {
for(int x = 0; x < 3; x ++) {
switch(x) {
case 0: cout << "zero" << endl;
case 1: cout << "one" << endl;
case 2: cout << "two" << endl;
}
cout << endl;
}
}
[/edit]
-
> Why is Hello World getting outtputted when the case value is not met?
Because of the way the case statements are arranged: since there is no break in the example, x will make the switch jump to the code at case 0, and it keeps running until all cases after that are accounted for.
-
a switch statement execution begins at the case label that evaluates the condition to true and ends at the end of the switch statement or when a break statement is found.
Consider it this way; once the proper case label is found, no more case labels will be tested. Everything between there and the end of the switch statement will be executed unless you use a break.
Some people find switch statements odd because they "force" them to use the break statement repeatedly. This couldn't be further from the truth. Sometimes the desirable effect is exactly to have the code process across all case labels, starting at the one that evaluates to true.
Code:
int stage = 3;
switch (stage) {
case 1:
fixMotherboardToCase();
case 2:
fixGrahicsToMotherboard();
case 3:
fixHardDriveToCase();
case 4:
fixPowerToCase();
connectHardDriveToPower();
case 5:
PaintLogoOnCase();
default:
Ship();
}
And even more powerful is the notion that you can have both worlds, by having switch statements with break statements on some labels and not on others.
-
. . . ignoring the fact that case label values must be integral constants. (And that since C++ is case-sensitive, Case won't work. :) )
-
-
You forgot a semicolon. :D
Your textbook should explain this. You don't need to read everyone's two cents.
-
that's what when I write code on the quick reply box :p
-
Why on Earth would the designers of C++ just go on to ignore the rest of the case conditions? That is about the same as ignoring in an if else statement. What was there reasoning behind this? Am I just missing something?
-
Consider a switch statement as a production line. When you put something on the catwalk, it keeps on going until either:
1. You stop it from moving because of some condition,
2. You reach the end of the line.
Without break statements, you would have to produce spaghetti code involving lots of elseif statements.
-
Still did not answer my question on why the devlopers did this. What was there rational? It seems stupid. Its like have multiple ifs and if one if is meet it executes the rest of the if statements even though the condition is not meet.
-
It did answer your question. The problem is that you are comparing switch statements to if statements. Don't do that. Same type of argument could arise from comparing while with for statements.
Switch statements offer a program flow that can be matched with if and else. However, it would be cumbersome, considerably harder to code, wouldn't convey the true meaning of what the original programmer intended and would be much more prone to error, given all of the above.
If this is still confusing you, don't look at case labels as conditions. The condition is present after the switch keyword inside parenthesis. Look at case labels as entry points of a program flow redirection.
A switch statement is a construct with one of two purposes.
1. It can either be used is a... switch with many positions that performs a set of tasks for a given position and then exits, not doing any of the other tasks for the other switch positions. (this is the most usual scenario. A switch statement with breaks on most, if not all case labels)
2. Or it can be used as a workflow type of construct. (A switch statement with few, if any, break statements)
Imagine a car production line on a car factory.
- Every stop in which a robot or human either attaches a door to the car or places the windshields, or paints the car, or something else, is a case label.
- Some work is done on the car on that case label. But the production line didn't stop. The car moves on to the next case label. And it goes on doing this until it reaches the end of the production line and is ready to go to the road.
- On every case label of this car production line, you can set situations on which the car breaks off the production line. The window that was being attached has a scratch, the robot leaked oil,... You create a break, moving the car off the production line.
- You can also insert a car that is partially built on any case label on the production line. However, you don't want to insert a car with windows on the case label that attaches windows. You probably want to place it on the next case label.
A switch statement was not a "stupid" thing someone just decided to include on a programming language to make fun of poor programmers. It is in fact a extremely useful construct.
-
> Still did not answer my question on why the devlopers did this
It's a source of ongoing debate - it's just the way it is (like why some operators have the wrong precedence).
http://www.cs.bell-labs.com/who/dmr/chist.html
http://www.lysator.liu.se/c/ (when it's up).
On the plus side, it allows Duff's device to be implemented :D
http://www.catb.org/jargon/html/D/Duffs-device.html
On the minus side, it allows Duff's device to be implemented :rolleyes:
> Its like have multiple ifs
But only when each case has a break, does it resemble an if/else if statement.