Search code examples
c++switch-statementlanguage-design

Switch without case


Today, I accidentally discovered that my compiler doesn't complain when writing code inside of a switch statement without a case. (It did complain about the lack of case statements, but after adding one after the code, there wasn't so much as a warning to let me know the code was useless.)

I'm trying to figure out if there's a purpose to allowing the following code, or if it's just one of those things where "it's more work to restrict it, so it's allowed".

#include <iostream>
void foo() {
   std::cout << "foo" << std::endl;
}
 
int main()
{
   for (int a = -10; a < 10; ++a)
   {
      switch(a)
      {
         foo();
      case 4:
         std::cout << "4" << std::endl;
      }
   }
}

This now outputs "4" as expected when a == 4, and it never outputs foo. So the question is, is there some (potentially esoteric but useful) reason to allow for the statement foo(); before the first case? I know for sure I'm not allowed to declare and initialize variables there.

FWIW, I have tested this on both MSVC 2012 and GCC 4.8.1, and they're yielding the same behavior. Surprisingly, they also all don't output a warning.

I also tried gcc with -Wall. On an antique version of GCC (3.3.2 on AIX) I got an unreachable code warning. On a more recent version (4.5.3 on Cygwin) I got no warning.


Solution

  • Yes, the behavior is as designed in the language and you can add code in different places. Switch statements are much more complicated than the look, and they allow for quite esoteric code, whether it makes sense or not.

    If you want to spend some time looking at some strange uses of switch and the location of cases, you can look at the implementation of coroutines in the boost asio library. You can write a small function with the macros, compile and see what the generated code (after macro expansion) looks like.