Is it bad practice to initialize variables inside a specific case of a switch?
I have quite a few variables that is only relevant for one of my cases, and can't seem to find any info on this.
Thanks :)
Is it bad practice to initialize variables inside a specific case of a switch?
I have quite a few variables that is only relevant for one of my cases, and can't seem to find any info on this.
Thanks :)
Why not only declare them for the case where they're relevant?
switch (something)
{
case 1:
do_something();
break;
case 2:
{
int x = 12;
do_something_else(x);
break;
}
}
Don't miss out the curly braces used in case 2:
to create a sub-scope. Thus, variable x is local to case 2
In general, I would say if one of your cases is complex enough that it requires it's own variables that aren't used elsewhere, it should probably actually become it's own function.
If you have something like this:
class X { X() {...} /* and other stuff */ };
switch(a)
{
case 1:
X x;
... using x here ..
break;
case 2:
...
break;
....
}
then x
will be destroyed at the end of the switch
brace. Which won't be a great idea, since for cases other than 1, it won't have been initialized. [This example won't compile, because the compiler DETECTS that this will happen, and gives an error!]
So use braces to wrap it:
case 1:
{
X x;
... using x here ..
}
break;
case 2:
...
break;
....
Now X is destroyed before the break
, which is fine.
Other than this part, there's nothing wrong with having local variables in a specific case. In fact, I'd say it's a GOOD thing [but perhaps better is to write a small function!]