Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch/Case statements in C++

Tags:

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;
    }
}
like image 596
user320723 Avatar asked May 26 '10 06:05

user320723


1 Answers

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

like image 145
Greg Hewgill Avatar answered Oct 18 '22 18:10

Greg Hewgill