machinery
machinery

Reputation: 6290

Control Flow of switch statements without breaks

I have a question regarding the following switch statement:

#include <iostream>
using namespace std;

int main()
{
    int x = 1;

    switch (x)
    {
        case 1:
            cout << "x is 1" << endl;
            //break;
        case 2:
            cout << "x is 2" << endl;
            //break;

        default:
            cout << "x is something else" << endl;
    }

}

With break it works as expected but when I comment out the breaks the output is:

x is 1
x is 2
x is something else

I expect the output to be

x is 1
x is something else

because x == 1 and case 1 is executed. Without a break it also checks case 2 which should not be executed because x != 2. At the end default is executed.

Why is case 2 executed in this case?

Upvotes: 0

Views: 894

Answers (1)

Abstraction
Abstraction

Reputation: 1652

case labels of switch operator don't "check" anything, they're basically goto labels. One could even write:

const int count = 12;
char dest[count], src[count] = "abracadabra", *from = src, *to = dest;
int n = 1 + (count - 1) / 8;
switch (count % 8) {
    case 0: do { *to++ = *from++;
    case 7:      *to++ = *from++;
    case 6:      *to++ = *from++;
    case 5:      *to++ = *from++;
    case 4:      *to++ = *from++;
    case 3:      *to++ = *from++;
    case 2:      *to++ = *from++;
    case 1:      *to++ = *from++;
               } while (--n > 0);
}
printf("%s\n", dest);

Upvotes: 2

Related Questions