user320723
user320723

Reputation: 133

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

Upvotes: 13

Views: 972

Answers (4)

Jake Petroules
Jake Petroules

Reputation: 24190

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.

Upvotes: 0

Phong
Phong

Reputation: 6768

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

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 994401

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

Upvotes: 18

poeschlorn
poeschlorn

Reputation: 12440

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

Upvotes: 0

Related Questions