Search code examples
c++scopingswitch-statement

Scoped case statement in C++: purpose of cross-scope case labels?


I have a bug in my current code that I have been banging my head against for a couple days. I'll post the summary version of the code below (not my actual code, but it still compiles).

#include <iostream>

using namespace std;

int main()
{
  int x = 7;

  switch(x)
  {
    case 1:
    {
      case 2:
      cout << "hi";
    }
  }
}

I like to sometimes introduce a tighter scope to my switch cases so local variable names don't interfere with ones I've used earlier. Apparently I had a phone call to answer or something one day and didn't finish writing the case statement as I wished, but later on was certain that I had. case 2 should have actually been in a nested switch, not as part of the original outter switch (for those wondering, I use named constants in my code, not just magic numbers). On g++, I didn't get a warning or error when compling without any options.

My question: why allow cross-scope case jumps from a switch? What purpose does it serve?


Solution

  • Duff's Device is hardly the "purpose" of cross-scope case labels as already suggested, it is merely an exploitation of it.

    The truth is probably that it serves no intentionally designed purpose, but is merely an artefact of the most simple possible implementation that works. The design is such that the switch-case construct can do exactly what is reasonable, but does not explicitly protect you from the unreasonable either.