Question

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 several compilers, and they're all yielding the same behavior. Surprisingly, they also all don't output a warning.)

Was it helpful?

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.

OTHER TIPS

From the MSDN:-

Declarations can appear at the head of the compound statement forming the switch body, but initializations included in the declarations are not performed. The switch statement transfers control directly to an executable statement within the body, bypassing the lines that contain initializations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top