1

I want to return by reference to a variable that's inside a switch, like for example:

sometype & getbar();

void foo() {
        switch ( {statement} ) {
        case {statement}:
            sometype & handle = getbar();
        ...

But I'm getting compiler errors:

initialization of 'identifier' is skipped by 'case' label

initialization of 'identifier' is skipped by 'default' label

And it looks like it's not possible to do this:

void foo() {
        sometype & handle;
        switch ( {statement} ) {
        case {statement}:
            handle = getbar();
        ...

Because a reference variable requires initialization.

Is there a way to do this with keeping the switch statement?

Community
  • 1
  • 1
shinzou
  • 5,850
  • 10
  • 60
  • 124

1 Answers1

7

Yes, there is. Enclose the body of the case statement in brackets, like this:

case {statement}:
{
    sometype & handle = getbar();
    ...
}
owacoder
  • 4,815
  • 20
  • 47
  • Woah it works! What's the difference? – shinzou Dec 11 '15 at 17:17
  • @kuhaku, Cases are special labels and C++ doesn't let you skip over variable initialization by jumping to a label. – chris Dec 11 '15 at 17:18
  • @kuhaku - See: http://stackoverflow.com/a/92439/18882 – Steve Fallows Dec 11 '15 at 17:19
  • @kuhaku - case statements are like labels, jumped to by the switch condition. This means that the entire switch expression has a single scope. The compiler complains if there are any variables whose initialization could be "skipped over" in this scope, so by creating a new scope with the brackets, the variable initialization error/warning is resolved. – owacoder Dec 11 '15 at 17:20