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?
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.