C++ Scoping Question

jgbishop

Senior member
May 29, 2003
521
0
0
Suppose I have a switch statement like in the following pseudo-code (sorry about the formatting - the lack of attaching inline code in this forum is atrocious):

switch(foo)
{
case 1:
int bar = 0;
break;

case 2:
char bar = 'a';
break;
}

Will I get a 'variable redefinition' warning when compiling this (since 'bar' is both an int and a char)? Or is the scope of a local variable constrained to a case statement?

In other words, does a case constitute a 'block' of code?
 

Armitage

Banned
Feb 23, 2001
8,086
0
0
Originally posted by: jgbishop
Suppose I have a switch statement like in the following pseudo-code (sorry about the formatting - the lack of attaching inline code in this forum is atrocious):

switch(foo)
{
case 1:
int bar = 0;
break;

case 2:
char bar = 'a';
break;
}

Will I get a 'variable redefinition' warning when compiling this (since 'bar' is both an int and a char)? Or is the scope of a local variable constrained to a case statement?

In other words, does a case constitute a 'block' of code?

I dunno - if it doesn't you can always add braces, try it and see - report back :p

 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
Not unless you use { } to define a new scope as Armitage suggests.

Of course any local variables you create in the case will "evaporate" when you leave that scope.
 

Thyme

Platinum Member
Nov 30, 2000
2,330
0
0
Originally posted by: DaveSimmons
Not unless you use { } to define a new scope as Armitage suggests.

Of course any local variables you create in the case will "evaporate" when you leave that scope.

Chances are that should work but won't be a useful solution since you must have a reason for being able to refer to them by the same name. What exactly is the purpose of doing it that way?
 

statik213

Golden Member
Oct 31, 2004
1,654
0
0
Originally posted by: Thyme
Originally posted by: DaveSimmons
Not unless you use { } to define a new scope as Armitage suggests.

Of course any local variables you create in the case will "evaporate" when you leave that scope.

Chances are that should work but won't be a useful solution since you must have a reason for being able to refer to them by the same name. What exactly is the purpose of doing it that way?

You might want to look into union
here

You could then define bar as a union that has both an int and char member and set the appropriate one in the case.... what you would do afterthat is beyond me....
(note: I think union will work only with primitive and structs composed of primitive).
 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,589
5
0
Without using the brackets as Armitage showed, a complier should complain about the use of the int declaration within the case statement.