tags:

views:

161

answers:

4

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;
    }
}
A: 

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...

poeschlorn
+15  A: 

This is Duff's Device, which is an old, clever technique for jumping into the middle of a loop.

Greg Hewgill
clever...? I think it more depend of the case. I wont use it if it compromize the readability of the code. Can you give me a more concrete example where it can be apply?
Phong
@Phong: Evil things can still be clever.
Greg Hewgill
Sir, you appear to have done your homework! +1 from me!
Nikos Steiakakis
Just because something's clever doesn't mean it is necessarily good. ;)
Jake Petroules
+1: For knowing "Duff's Device". -0.1 for the usage of the word "Clever" ;-)
Johnsyweb
"This code forms some sort of argument in that debate, but I'm not sure whether it's for or against." - Duff. That has always been one of my favorite quotes.
Dennis Zickefoose
For those that don't consider it clever, note that this is an optimization technique, not to be used in general, but rather only when performance was critical. It allows to manually perform a partial unroll of a tight loop regardless of the number of iterations.
David Rodríguez - dribeas
It's clever and hard to read. I do hope that my compiler will unroll the loops better than I will :)
Matthieu M.
A: 

Switch does not evaluate/understand the source code. It is just a command here to jump directly to the source code label case 4

Phong
A: 

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.

Jake Petroules