2

I have encountered an interesting peculiarity while playing with code. I am using Eclipse CDT 4.5.2 with Cygwin and C++14 turned on (-std=c++14). Variable initialization inside CASE's is normally prohibited, but the following code compiles:

switch( int switchStatement = 11)
{
    default:
        ++j;
        break; // break is optional, still compiles even if omitted
    case 11:
        int caseVariable = 0;
        ++j;
}

If another CASE is added, then exception "jump to case label" is raised.

switch( int switchStatement = 11)
{
    default:
        ++j;
    case 11:
        int caseVariable = 0;
        ++j;
    case 12: // exception
        ++j;
}

Could somebody explain me how it all works?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

1 Answers1

1

why you are getting error in second case but not getting error when you declare a variable in last case statement??

Because it's a rule of C++ that a jump cannot pass over a variable declaration in the same scope. So when you jump to case 2, you pass over the variable declaration in case 1. But the variable declaration in the last case is OK, because it is never jumped over.

The reason for the rule is that if you allowed a jump over a variable declaration it would be very hard for the compiler to work out whether to call a destructor for that variable. If you had jumped over the variable declaration you would not need to call the destructor, if you had not jumped then you would.

The Variable declared and initialized in one case statement can still be visible in other case block but they will not be initialized because the initialization code belongs to another case.

In C++ Problem is of scope. Here, case statements are "labels". Hence, compiler will treat them for making jump from one statement to another. In this particular example, compiler won't understand how to proceed further. To solve this problem you can include the code inside the case into a {} block. The extra { and } mean that the compiler has no trouble working out when to call destructor. Therefore, providing scope or curly brackets to that particular case statement while declaring new variables is important.

Alex Morrison
  • 405
  • 3
  • 12