Switch/Case statements in C++
Regarding the switch/case statement in the C++ code below: "Case 1" is obviously false, so how/why does it enter the do-while loop?
#include <iostream>
using namespace std;
int main() {
int 开发者_开发问答test = 4;
switch(test) {
case 1: do {
case 2: test++;
case 3: test++;
case 4: cout << "How did I get inside the do-while loop?" << endl; break;
case 5: test++;
} while(test > 0);
cout << test << endl;
}
}
This is Duff's Device, which is an old, clever technique for jumping into the middle of a loop.
I've not tested it, but in general the do/while loop should be entered as long you don't have a "break" statement implemented...
Switch does not evaluate/understand the source code. It is just a command here to jump directly to the source code label case 4
The reason you reach the do-while loop is because:
Switch statements start processing at the first label. If it does NOT hit a break statement, it will continue down through each label in succession until it does hit one (in which case it exits), or it has gone through each label and executed all the code within, then exits.
精彩评论