I have a rather long switch-case statement. Some of the cases are really short and trivial. A few are longer and need some variables that are never used anywhere else, like this:
switch (action) {
case kSimpleAction:
// Do something simple
break;
case kComplexAction: {
int specialVariable = 5;
// Do something complex with specialVariable
} break;
}
The alternative would be to declare that variable before going into the switch
like this:
int specialVariable = 5;
switch (action) {
case kSimpleAction:
// Do something simple
break;
case kComplexActi开发者_JS百科on:
// Do something complex with specialVariable
break;
}
This can get rather confusing since it is not clear to which case
the variable belongs and it uses some unnecessary memory.
However, I have never seen this usage anywhere else.
Do you think it is a good idea to declare variables locally in a block for a singlecase
?If specialVariable is not used after the switch block, declare it in the "case" block.
In general, variables should be declared in the smallest possible scope it will be used.
If the switch
statement becomes unmanageably huge, you may want to convert to a table of function pointers. By having the code for each case in separate functions, you don't have to worry about variable declaration and definitions.
Another advantage is that you can put each case
function into a separate translation unit. This will speed up the build process by only compiling the case
s that have changed. Also improves quality by isolating changes to their smallest scope.
Yes define variables in the narrowest scope needed.
So example 1 is preferred.
I'm all for
case X:
{
type var;
...;
}
break; // I like to keep breaks outside of the blocks if I can
If the stuff in there gets too complicated and starts getting in the way of your ability to see the entire switch/case as a switch/case then consider moving as much as you can into one or two inline functions that get called by the cases code. This can improve readability without throwing function call overhead in there.
Agree with Max -- smallest possible scope as possible. That way, when the next person needs to update it, he/she doesn't need to worry about if the variable is used in other sections of the switch statement.
My own rule for switch statements is that there should be a maximum of a single statement inside each case, excluding a break. This means the statement is either a an initialisation, an assignment or a function call. Putting any more complex code in a case is a recipe for disaster - I "fondly" remember all the Windows code I've seen (inspired by Petzold) which processed message parameters in-line in the same case of a windows procedure.
So call a function, and put the variable in there!
精彩评论