Declaring Variables in Switch Statements

There you are, happily programming away, when suddenly you get a compile error:

error: jump to case label
error: crosses initialization of 'int x'

“Huh?” You say, peering at the computer screen. Your code looks fine, so what does it mean?

Look closely at your switch statement. A switch statement contains case labels, which provide options to do different things after checking the value of a variable. However, what you may not realise is that the contents of each of these case labels actually exists in the same scope.

Why does scope matter?

If you declare a variable after a case label, you are actually declaring that variable for all subsequent labels without realising it.

This could lead to you trying to declare the same variable twice (if you’re doing similar things for each case), or worse, for you to inadvertently change the value of a variable under another case.

To stop you from doing this, the compiler flags an error and stops compilation.

Oh right. But how do I fix it?

You can still declare variables in switch statements, you just have to put curly brackets around the code after the case label.

Compare the two examples below. The first one generates an error. The second lets you compile and move on.

1. This generates a compile error:

switch (y)
{
case 0:
    int x = 42;
    cout << "I declared variable x." << end;
    break;
case 1:
    cout << "Variable x is still in scope!" << end;
    break;
default:
    break;
}

2. This compiles successfully:

switch (y)
{
case 0:
    {
        int x = 42;
        cout << "I declared variable x." << end;
    }
    break;
case 1:
    cout << "I don't know about variable x." << end;
    break;
default:
    break;
}