1

I understand why I can't define a variable under 'case', but why can I define one under 'default' then? I thought it was another label, just like 'case'.

switch(myVar)
{
    case 0:
        int a = 12; //error
        break;
    default:
        int b = 42; //OK
}
Valentin
  • 1,108
  • 8
  • 18

4 Answers4

4

Try reordering your cases:

switch(myVar)
{
    default:
        int b = 42; // error
        break;
    case 0:
        int a = 12; // ok
}

Now you will see the compiler complain about b, and not a. There is nothing magical about default, it's just that if you define the variable in the last case statement, then there is no way to skip over the initialization of that variable, and so it is perfectly fine to do so.

You can always scope your cases, so that the variables can't be accessed outside of a case, if that was your intention:

switch(myVar)
{
    case 0: {
        int a = 12;
    }
    break;
    default:
        int b = 42;
}
Rakete1111
  • 47,013
  • 16
  • 123
  • 162
3

You can't define it under case 0 because a jump to the default label (which is what a switch statement does) will skip the initialization of a.

C++ forbids such skipping. If there's variable being initialized in a block, then control cannot go to a point inside the block that is past the initialization, without preforming it.

However, since int is a type without a constructor, then you can define the variable if you omit the initializer:

switch(myvar)
{
    case 0:
        int a; //OK too
        break;
    default:
        int b = 42; //OK
}
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
0

Initialize all your variable before the switch statement.

int a = 0;
switch(myVar)
{
    case 0:
        a = 12; //now ok
        break;
    default:
        int b = 42; //OK
}

It has got something to do with C++ standard. More info here Cross initialization

digitalis
  • 125
  • 1
  • 12
0

You can also do that:

switch(myVar)
{
    case 0:
    {
        int a = 0;
    }
    break;
    default:
        int b = 42; //OK
}
Raindrop7
  • 3,889
  • 3
  • 16
  • 27