Case scope in switch statements


Is it's scope confined to that single case?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
char ch;
switch(ch)
{
    case '1':
        using namespace common::section1; //only this case??
        break;
    
    case '2':
        using namespace common::section2; //I shoudn't be able to use section1 without specifying it here
        break;
    
    default:
        break;
}


Thanks for the help.
cases are just labels (same as goto labels, syntactically) in the one compound statement (aka block) that begins at line 3 and ends at line 14. They do not influence scope.

Some style guides even recommend using a separate compound statement for each case label:
1
2
3
4
5
   case '1': {
        using namespace common::section1; //only this case??
        break;
   }
   case '2':...
so, I should set the scope of definitions at the beginning of the switch block? Alright then.

I used to use seperate blocks for each case, but I had trouble with them breaking correctly... it would fall through even though it was supposed to break.
I just want to make sure...

So, if I have a case:

1
2
3
4
5
6
7
8
9
10
11
case 'a':
{
    //...
    break;
}

case 'b':
{
    //...
}
break;


The way I understand, case b is the right way to break, right? I think the problems I was having before were because I was breaking inside the block of the case.
Either way to break is fine.
What do you mean by "set the scope of definitions", though?
When you use { and } you create a local block, so you can stick your using namespace and local variables in there. (Caveats apply.)
@Duos:

That's interesting, because in the past, I have written switch cases with the break within the block. It worked for the most part, but for some reason there would be a specific part where it would ignore the break...

I don't know, I emplemented a lot of switch cases and nested switch cases in a menu I'm working on and it works perfectly (better!) so far...

Oh well. I suppose I'l never know what happened back then.
Cubbi: > cases are just labels (same as goto labels, syntactically) ... They do not influence scope.

Perhaps the most famous illustration of this:
http://en.wikipedia.org/wiki/Duff's_device#Original_version
Dam that's ingenious...
Topic archived. No new replies allowed.