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 kComplexAction:
// 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 single case
?
Declaring a variable inside a switch block is fine. Declaring after a case guard is not.
If the cases were allowed to contain variables, the compiler would have to emit code that first evaluates these expressions and then compares the switch value against more than one other value. If that was the case, a switch statement would be just a syntactically-sugarized version of a chain of if and else if .
Only Integral values are allowed inside the case label, and the expression inside the switch must evaluate to a single integral constant. Variables are not allowed inside the case label, but integer/character variables are allowed for switch expression. Break and default are optional.
If a programmer declares variables, initializes them before the first case statement, and then tries to use them inside any of the case statements, those variables will have scope inside the switch block but will not be initialized and will consequently contain indeterminate values.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With