Why is the case argument allowed inside the block for another case?

I came across a code that looks like this:

switch(i) { case 2: { std::cout << "2"; break; case 3: std::cout << "3"; break; } case 4: { std::cout << "4"; break; } } 

Note that case 2 opens a block with a curly brace, which closes only after case 3 . At first, it looked like a typo, which could cause a compiler error or, even worse, ignore case 3 . But it works fine in C ++ and outputs 3 if I'm 3. I came from a java background, so my understanding of logical blocks in C ++ may be missing. So my question is: is this intentional behavior?

+8
c ++ switch-statement
source share
2 answers

You can, but should not, abuse case labels in a switch much worse than this - and much worse than a Duff Device . Duff Device has the dubious privilege of being almost believable and can still be considered an abuse of switch .

Not all switch abuses can claim credibility. For example, this compiles as C or C ++, even with strict warnings:

 #include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char **argv) { unsigned seed; if (argc == 2) seed = atoi(argv[1]); else seed = time(0); printf("seed: %u\n", seed); srand(seed); int i = rand() % 10; int j = 21; int k = 37; printf("i: %d\n", i); switch (i) { case 1: for (j = 10; j > i; j--) { case 2: printf("case 2:\n"); for (k = j - 1; k > 0; k--) { case 6: printf("case 6:\n"); default: printf("%d-%d-%d\n", i, j, k); } case 5: printf("case 5:\n"); printf("%d-%d\n", i, j); break; } break; case 3: printf("case 3:\n"); break; } return 0; } 

Argument processing allows you to set the seed so that you can reproduce the results if you want. I will not argue that this is useful; indeed, this is not useful. Note that break inside loops interrupts the loop, not switch .

Basically, case (and default ) labels should be in the switch and connected to the innermost switch shell. There are other restrictions on them. You must be careful not to jump over initialization variables, etc. (Therefore, j and k defined outside switch() ). But for the rest, they are just shortcuts, and control will flow to them when it "fits."

+9
source share
Operator

switch in C / C ++ is the famous goto (with some optimization benefits).

As a result, you can do as much with case labels as with goto labels. In particular, a jump inside the block is allowed if you do not bypass any initialization of variables.

+5
source share

All Articles