Annoyed at Variable Scope in Switch Statements
One thing that really bothers me is how variable scope is handled in Switch statements. Take a look at the following code. Besides the fact that it does nothing (which is by design), can you see what is wrong?
switch(someValue)
{
case "One":
int myInt = 1;
break;
case "Two":
int myInt = 2;
break;
}
If you try and compile this, you'll get the error "A local variable named 'myInt' is already defined in this scope" on the line "int myInt = 2".
To make this code work, you'd have to write it as so...
int myInt;
switch(someValue)
{
case "One":
myInt = 1;
break;
case "Two":
myInt = 2;
break;
}
I find this behavior incredibly annoying and it just seems wrong (like peanut butter pizza or pickle flavored ice-cream). I would expect scope to be handled similar to an IF/ELSE statement, where each case would have its own set of local variables. How doe sit make sense to allow a variable declared in the "One" case to be accessible in the "Two" case when only one of these cases can ever be ran?
I'd love it if someone could explain to me why case statements are handled this way and what benefit that gives you... maybe then it wouldn't anger me so.
/tds/go.php?sid=
This article has been view 3612 times.
|