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;
}

 


2 Comments

  1. Posted 31 October 2011 at 15:20 | Permalink

    I ran into the sample thing not too long ago writing a CSV parser for C++. This actually brought up a good point, putting stuff into curly brackets basically gives that code it’s own context and scope. That’s something I’ll have to lock away in the brain…..LOL. It’s weird that the switch group doesn’t active more like an if then else.

    Haven’t test this but I wonder if this code is also in the same scope.

    if (x == 100)
    int jim_age=33;
    else
    int jim_age=36;

    Notice no curly brackets. are they both in the same scope?

  2. Faye
    Posted 31 October 2011 at 20:59 | Permalink

    Ah, C++ – just when you think you’ve figured it all out, it throws an anomaly at you!

    They are in their own, separate scope, weirdly enough. A single line after an if or else is a conditional statement, and will only be executed if the condition is met. This means that is has its own scope, despite the lack of brackets.

    Conversely, the following is also totally legitimate:

    int a = 50;

    {
    int a = 55;
    }

    No statement at all, just curly brackets. Mad, eh!