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."
Jonathan leffler
source share